2-4.4 Intro Python

Working with Files

4.1 File import in Jupyter Notebooks
4.1 File open() and .read()
4.2 File Read as a list with .readlines()
4.2 File Closing to free resources with .close()
4.3 File Read a line at a time with .readline()
4.3 Remove characters using .strip()
4.4 .write() data to a new local file
4.4 File .write() with .seek()
4.4 File append


> Student will be able to
4.1 Import files in Jupyter Notebooks
4.1 Open and .read() local files in memory
4.1 .read() a specific number of characters
4.2 Use .readlines() to read data from file as a list of lines
4.2 Use .readlines() to read data from file as a list of lines
4.3 Use .readline() to read data from file a line at a time
4.3 Use .strip() to remove new line characters
4.4 .write() data to a new local file
4.4 Use .seek() to set file read or write location
4.4 Use file append mode

 

Concepts

writing to a file opened in write mode 'w' or 'w+'

>python poem_file = open('poem.txt', 'w') poem_file.write("Hello World!\n")

view video

write mode: 'w'

write mode plus read: 'w+'

'w' and 'w+' modes will create a new file or overwrite existing files

All previous data will be lost

 

Examples

In [1]:
# [ ] review and run example
# - creates a new local file or overwrites the local file (makes it blank)
new_file = open('new_file.txt', 'w')
In [2]:
# [ ] review and run example to write some text to the file
new_file.write("This is line #1 with 'w'\nThis is line #2 with 'w'\nThis is line #3 withn 'w'!\n")
Out[2]:
77
In [3]:
# [ ] review and run example
# - close file and re-open in read mode 
# - head pointer is at start of file
new_file.close()
new_file = open('new_file.txt', 'r')
In [4]:
# [ ] review and run example to see what was written to the file
new_text = new_file.read()
print(new_text)

new_file.close()
This is line #1 with 'w'
This is line #2 with 'w'
This is line #3 withn 'w'!

'w+' means the file is in write plus read mode

  • after any write, the pointer is at the end of text that has been written
  • to read the entire file, the pointer needs to be at the beginning of the file - see .seek() below to set the file pointer

 

Task 1

create a local file

open in 'w' mode

  • open inner_planets.txt in write mode 'w' to create a local file
  • write the first four planets from the sun in earth's solar system (Mercury, Venus, Earth, Mars) on separate lines
  • close the file and re-open in read mode 'r'
  • use .read() to read the entire file contents
  • print the entire file contents
In [21]:
# [ ] open planets.txt in write mode

#Answer:
new_file = open('planets.txt', 'w')
In [22]:
# [ ] write Mercury, Venus, Earth, Mars on separate lines
#Answer:
new_file.write("Mercury\nVenus\nEarth\nMars\n")
#new_file.write("Venus\n")
#new_file.write("Earth\n")
#new_file.write("Mars\n")
Out[22]:
25
In [23]:
# [ ] close the file and re-open in read mode
#Answer:
new_file.close()
new_file = open('planets.txt', 'r')
In [24]:
# [ ] use .read() to read the entire file contents
#Answer:
new_text = new_file.read()
In [25]:
# [ ] print the entire file contents and close the file
#Answer:
print(new_text)
new_file.close()
Mercury
Venus
Earth
Mars

 

Concepts

using .seek(0)

setting the pointer to beginning of file

>python new_file.seek(0) new_contents = new_file.read() print(new_contents)

view video

using .seek() to set the read/write pointer to beginning of file

new_file.seek(0) moves the file read\write pointer to the start of the file

 

Examples

seek() with 'w+'

In [15]:
# [ ] review and run example
# creates a new local file or overwrites the local file (makes it blank)
new_file = open('new_file.txt', 'w+')

write plus read 'w+'
'w+' overwrites existing files of the same name - rendering the file blank
the file is writeable and readable

In [16]:
# [ ] review and run example to see what was written to the file 
# - 'w+' overwrites, we can read, but the file is ***BLANK***
new_text = new_file.read()
print(new_text)

In [17]:
# [ ] review and run - write to the blank file
new_file.write("This is line #1 with 'w+'\nThis is line #2 with 'w+'\n")
Out[17]:
52
In [18]:
# [ ] review and run example - read and print (Note: the pointer is at the end of the file - result = empty string)
new_text = new_file.read()

print(new_text)

Expected: prints empty string above

pointer was at end of file where there is nothing to read

seek(0)

sets the pointer to the beginning of the file, enabling read() to input the entire file contents

In [19]:
# [ ] review and run example - sets pointer to beginning of file
new_file.seek(0)
Out[19]:
0
In [20]:
# [ ] review and run example - now read starts from beginning of file
new_text = new_file.read()
print(new_text)
This is line #1 with 'w+'
This is line #2 with 'w+'

In [26]:
# # [ ] review and run example - clean up and close file
new_file.close()

 

Task 2

using .seek(0) on a local file in write plus read mode 'w+'

open outer_planets.txt in 'w+' mode (write plus read)

  • open outer_planets.txt in write plus read mode 'w+'
  • write four outer planets in earth's solar system (Jupiter, Saturn, Uranus, Neptune) on separate lines
  • use .seek() to move the pointer to the start of the file
  • use .read() to read the entire file contents
  • print the entire file contents and close the file
In [27]:
# [ ] open outer_planets.txt in write mode 'w+' 
#Answer:
new_file = open('outer_planets.txt', 'w+')
In [28]:
# [ ] write four outer planets in earth's solar system (Jupiter, Saturn, Uranus, Neptune) on separate lines
#Answer:

new_file.write("Jupyter\nSaturn\nUranus\nNeptune")
Out[28]:
29
In [29]:
# [ ] use .seek() to move the pointer to the start of the file
# [ ] use .read() to read the entire file contents
#Answer:
new_file.seek(0)

new_text = new_file.read()
In [30]:
# [ ] print the entire file contents and close the file

#Answer:
print(new_text)
Jupyter
Saturn
Uranus
Neptune

 

Concepts

using .seek() offset and whence

setting the pointer in a file with positive offset values and whence location

>```python new_file.seek(13) new_contents = new_file.read() print(new_contents)

```python
new_file.seek(0,2)

view video

using .seek() to set the read/write pointer in a file

offset values and whence arguments

.seek() can set the pointer to a desired index from the beginning of the file
the example below moves to the character to offset 10 (the 11th character)

new_file.seek(10)

which is also written with an optional second argument, know as whence ("from where")

new_file.seek(10,0)

using 0 for whence starts the offset from the beginning of the file

>Note: the offset must be a positive integer in Python 3, so we cannot offset backwards from the end of the file

file.seek(offset, whence)

whence mode description
0 points to the beginning of the file
1 points to the current location
2 points to the end of the file & offset is always 0

using whence the index can be offset from either the beginning, current location or to the end of the file (where there is no offset applied)

 

Examples

seek to a specific location

In [31]:
# [ ] review and run - create, write, read and print a file
tips_file = open('code_tips.txt', 'w+')
tips_file.write('-use simple function and variable names\n-comment code\n-organize code into functions\n')
tips_file.seek(0)
tips_text = tips_file.read()
print(tips_text)
-use simple function and variable names
-comment code
-organize code into functions

In [32]:
# [ ] review and run example - setting a specific seek() index 
tips_file.seek(13)
# now read starts from 14th character of file
tips_text = tips_file.read()
print(tips_text)
unction and variable names
-comment code
-organize code into functions

In [33]:
# [ ] review and run example - string slicing on a read of an entire file
# read from the start
tips_file.seek(0)
tips_text = tips_file.read()

# slice from the 14th character to end
print(tips_text[13:])
unction and variable names
-comment code
-organize code into functions

 

Examples

seek() with optional whence argument

In [34]:
# [ ] review and run example - setting pointer to end of file with whence value = 2
tips_file.seek(0,2)
tips_file.write("-use seek(0,2) to set read/write at end of file\n")

# read from beginning of file - .seek(0,0) is same as .seek(0)
tips_file.seek(0,0)
tips_text = tips_file.read()
print(tips_text)
-use simple function and variable names
-comment code
-organize code into functions
-use seek(0,2) to set read/write at end of file

In [35]:
# [ ] review and run example - point to file beginning and overwrite 1st line
tips_file.seek(0)
tips_file.write('-use simple function and variable names\n'.upper())
Out[35]:
40
In [36]:
# [ ] review and run example - show new file contents
tips_file.seek(0,0)
tips_text = tips_file.read()
print(tips_text)
-USE SIMPLE FUNCTION AND VARIABLE NAMES
-comment code
-organize code into functions
-use seek(0,2) to set read/write at end of file

 

Task 3

seek() with optional whence argument

  • open a new file days.txt in write plus read mode 'w+'
  • write week days (Monday - Friday) on separate lines
  • use .seek() to move the pointer to the start of the file
  • use .read() to read the entire file contents
  • print the entire file contents and close the file
  • use .seek() to move the pointer to the end of the file and write the weekend days (Saturday & Sunday)
  • use .seek() to move the pointer to the start of the file
  • use .read() to read the entire file contents
  • print the entire file contents and close the file
In [37]:
# [ ] open a new file days.txt in write plus read mode 'w+' 
# [ ] write week days (Monday - Friday) on separate lines to the file
#Answer:
days_file = open('days.txt', 'w+')
days_file.write('Monday\nTuesday\nWednesday\nThursday\nFriday\n')
Out[37]:
40
In [38]:
# [ ] use .seek() to move the pointer to the start of the file
# [ ] use .read() to read the entire file contents
# [ ] print the entire file contents and close the file

#Answer:
days_file.seek(0)
days_text = days_file.read()
print(days_text)
Monday
Tuesday
Wednesday
Thursday
Friday
In [39]:
# [ ] use .seek() to move the pointer to the end of the file
# [ ] write the weekend days (Saturday & Sunday)
#Answer:
days_file.seek(0,2)
days_file.write("Saturday\nSunday\n")
Out[39]:
16
In [40]:
# [ ] use .seek() to move the pointer to the start of the file
# [ ] use .read() to read the entire file contents
# [ ] print the entire file contents and close the file

#Answer:
# read from beginning of file - .seek(0,0) is same as .seek(0)
days_file.seek(0,0)
days_text = days_file.read()
print(days_text)
Monday
Tuesday
Wednesday
Thursday
FridaySaturday
Sunday

 

Concepts

open a file in a writeable mode

view video

open a file in a writing mode, with: 'w', 'w+', 'r+', 'a', 'a+'

MODE Description
'r' read only mode
'w' write - overwrites file with same name
'w+' write and read mode - overwrites file with same name
'r+' read and write mode (no overwrite)
'a' opens for appending to end of file (no overwrite)
'a+' opens for appending to end of file (no overwrite) plus read

warning: 'w' and 'w+' modes will create a new file or overwrite existing files (deleting all file contents)

 

Concepts

writing to a file opened in additional write modes: 'r+', 'a', 'a+'

Writing is the same - pointers are different >```python poem_file = open('poem.txt', 'r+') poem_file.write("Hello World!\n")

```python
poem_file = open('poem.txt', 'a+') 
poem_file.write("Goodbye, this is the end of the file\n")

view video

read mode plus write 'r+' and append modes 'a', 'a+'

read plus mode 'r+' differs from write modes 'w', 'w+'

  • read plus doesn't blank out the file contents with an overwrite

append modes 'a', 'a+' differ from write modes 'w', 'w+'

  • append doesn't blank out the file contents with an overwrite
  • append pointer is set to the end of the file for every write
  • append plus (a+) is append mode, plus read mode
'r+', 'a', 'a+'
will not overwrite existing file content creating a blank file

 

Examples

append plus mode a+

In [ ]:
# [ ] review and run example - function writes to the open log argument
# loads funtion into memory but the funtion is not called
def logger(log):
    log_entry = input("enter log item (enter to quit): ")
    count = 0

    while log_entry:
        count += 1
        log.write(str(count) + ": " + log_entry + "\n")
        log_entry = input("enter log item (enter to quit): ")
        
    return count
    
In [ ]:
# [ ] review and run example: makes a blank file  (initialize/reset)

log_file = open('log_file.txt', 'w+')
log_file.close()
In [ ]:
# [ ] review and run example - opens the log_file before passing to logger() function call, below
# allows for calls below to run several times appending to the end of log_file

log_file = open('log_file.txt', 'a+')
In [ ]:
# [ ] review and run example - calls the above logger() function
# what happens running the cell above (a+) again before running this cell again? 
# what happens if log_file.seek(0) is run before an append?

logger(log_file)    

log_file.seek(0)
log_text = log_file.read()

print()
print(log_text)
log_file.close()

read plus mode r+

view video create a file that has one line: "Count is: x"
overwrite with new count at the x location (x is an integer)

In [ ]:
# [ ] review and run example - create a file with initial count of 0
count_file = open("count_file.txt", "w+")

count_file.write("Count is: 0")
count_file.seek(0)
print(count_file.readline().strip())

count_file.close()
In [ ]:
# [ ] review and run example - can rerun this cell
count_file = open("count_file.txt", "r+")

count_file.seek(0)
count_line = count_file.readline().strip()
print("BEFORE\n" + count_line)

# get the int character(s) after the colon and space, cast and increment
count = int(count_line[10:])+1

# write the incremented value to the file - overwrite before value
count_file.seek(10)
count_file.write(str(count))

count_file.seek(0)
print("\nAFTER\n" + count_file.readline().strip())

count_file.close()
In [ ]:
# [ ]  review funtion code for inc_count() funtion that reads file and updates the count
# the file always has 1 line that is The count is: N, where N is an integer
def inc_count(cnt_file):
    cnt_file.seek(0,0)
    cnt_line = cnt_file.readline().strip()
    cnt = int(cnt_line[10:])+1
    cnt_file.seek(10,0)
    cnt_file.write(str(cnt))
    return cnt
In [ ]:
# [ ] review and run example with call to function: inc_count() - **Run cell multiple times**
# opens file/prints initial value
count_file = open("count_file.txt", "r+")

count_file.seek(0)
count_line = count_file.readline().strip()
print("BEFORE\n" + count_line)

# call inc_count() to increase the count 5 times
for i in range(5):
    count = inc_count(count_file)
    count_file.seek(0)
    print("\nAFTER inc_count() call", i+1, "\n" + count_file.readline().strip())

count_file.close()

 

Task 4

append

  • Open task4_file.txt in append plus mode ("a+")
  • create a for item in range(5): loop, for each loop:
    • write to the file: "append #"+ str(item)+"\n"
    • use seek() to set the pointer to the beginning of the file
  • print the file contents using file .read() method after eiting the loop

in append mode the file should only write to the end of the file regardless of setting seek() location

In [ ]:
# [ ] complete the task
# Provided Code creates and populates task4_file.txt
task4_file = open('task4_file.txt', 'w+')
task4_file.write("Line1\nLine2\nLine3\n")
task4_file.close()
# [ ] code here

#Answer:

 

Task 5

read plus (r+) mode

read the provided code and complete the code as follows:

  • Run the provided code below to create/open, print and close task5_file.txt
  • Open task5_file.txt in append plus mode ("r+")
  • create a   for item in range(1,5): loop, then, during each loop:
    • write to the file: "append#" + str(item)+ "\n"
    • use .seek(item*18) to set the pointer to 18x's the loop count
      Note: starting the first loop, item is 1 if using range(1,5), seek will be set to 18, 36, 54, 72
  • print the file contents using file .read() method after exiting the loop

"r+" mode will write wherever the pointer is set - such as after a read or from using .seek()

In [ ]:
# [ ] complete the task
# Provided Code creates and populates task5_file.txt
task5_file = open('task5_file.txt', 'w+')
task5_file.write("Line---1\nLine---2\nLine---3\nLine---4\nLine---5\nLine---6\nLine---7\nLine---8\nLine---9\nLine--10\n")
task5_file.seek(0)
print("Before:\n"+ task5_file.read()+"\n")
task5_file.close()

# [ ] code here

#Answer:
In [ ]:
 

Terms of use   Privacy & cookies   © 2017 Microsoft