Edexcel International Advanced Level Computer Science, point 8.2.3
A text file stores data as characters on secondary storage, so that it survives after the program ends. You must be able to select and use methods for handling text files. (Check the PLS for the exact methods allowed.)
The process
a. Open
open(filename, mode) returns a file object.
| Mode | Meaning | If the file doesn't exist | If it exists |
|---|---|---|---|
"r" |
Read (the default) | FileNotFoundError |
Opens at the start |
"w" |
Write | Creates it | Erases the contents |
"a" |
Append | Creates it | Adds to the end |
"x" |
Create a new file | Creates it | FileExistsError (so nothing is overwritten) |
Add "t" (text, the default) or "b" (binary, for images and other non-text files) to a mode: "rt" is the same as "r", and "rb" reads raw bytes.
f = open("scores.txt", "r")
e. Close
Closing saves any buffered data and frees the file for others. Forgetting to close a file you wrote can lose data.
f = open("scores.txt", "r")
data = f.read()
f.close()
The with statement (recommended)
with closes the file automatically, even if an error occurs.
with open("scores.txt", "r") as f:
data = f.read()
# the file is closed here
b. Read from
with open("names.txt", "r") as f:
everything = f.read() # the whole file as one string
with open("names.txt", "r") as f:
first = f.readline() # one line (includes the \n)
with open("names.txt", "r") as f:
lines = f.readlines() # list of all lines
with open("names.txt", "r") as f:
# one line at a time (best for big files)
for line in f:
print(line.strip()) # strip removes the newline
- Each line ends with
\n, so use.strip()to remove it. - Reading a number gives a string: convert with
int()orfloat(). readline()returns an empty string""at the end of the file.
c. Write to
with open("output.txt", "w") as f:
f.write("Amy,87\n") # you must add \n yourself
f.write("Raj,92\n")
"w"erases what was there.write()takes a string: convert numbers withstr(). It doesn't add a newline.f.writelines(list_of_strings)writes several lines (also without newlines).
d. Append to
"a" adds to the end and keeps the existing contents.
with open("output.txt", "a") as f:
f.write("Sam,75\n")
Handling errors
try:
with open("data.txt", "r") as f:
text = f.read()
except FileNotFoundError:
print("The file was not found")
except PermissionError:
print("You may not open that file")
Working with structured data (CSV-style)
A comma-separated line can be split into fields:
# file "stock.txt" contains:
# pens,12
# rulers,30
stock = {}
with open("stock.txt", "r") as f:
for line in f:
item, quantity = line.strip().split(",")
stock[item] = int(quantity)
print(stock) # {'pens': 12, 'rulers': 30}
Worked example
Task: a shopping-list program must save the list when it closes and load it back when it starts. Write a function to save a list of items and one to load them, which copes with the file not existing yet.
def save_list(items):
with open("shopping.txt", "w") as f: # write mode: replaces the old list
for item in items:
f.write(item + "\n")
def load_list():
items = []
try:
with open("shopping.txt", "r") as f:
for line in f:
items.append(line.strip()) # remove the newline
except FileNotFoundError:
return [] # nothing saved yet
return items
save_list(["milk", "eggs", "bread"])
print(load_list()) # ['milk', 'eggs', 'bread']
- Write mode
"w"is right here: the whole list is saved each time, so the old copy should be replaced. write()doesn't add a newline, so"\n"is added to each item.- Each line is stripped when loading, so the items come back without
\n. FileNotFoundErroris handled, so the first run (before anything is saved) gives an empty list instead of crashing.withcloses the files safely.
Exam tip: know the three modes and what "w" does to existing data. Close files (or use with). Remember \n at the end of each line when reading and writing, and that file data is text, so convert numbers. Handle FileNotFoundError.
Check yourself
What is the difference between "w" and "a" mode?
"w" erases any existing contents before writing. "a" keeps the contents and adds new data to the end.
Why should files be closed?
To make sure all buffered data is saved and to free the file for other uses; using with does this automatically.
Why use .strip() when reading lines?
Each line ends with a newline character (\n), which strip() removes.
What exception occurs when opening a missing file in read mode?
FileNotFoundError.
What type is the data read from a text file, and what must be done to use it as a number?
It is a string, so convert it with int() or float().