Lesson 4 of 5 · Errors and Files · 2 min read · Updated
Reading files
Reading a whole file, going through it line by line, and coping when it is not there.
python
with open("students.txt", "w", encoding="utf-8") as f:
f.write("Priya,87\nArun,73\nMeena,94\n")
with open("students.txt", encoding="utf-8") as f:
for line in f:
name, marks = line.strip().split(",")
print(f"{name} scored {marks}")
Output
Priya scored 87
Arun scored 73
Meena scored 94
Looping over a file gives one line at a time — the best way to read, because even a huge file never has to fit in memory at once. Each line still ends with its \n, which is why strip() comes first.
Other ways to read
f.read()— the whole file as one string.f.readlines()— a list of all the lines.f.readline()— just the next line.
When the file is missing
python
try:
with open("missing.txt", encoding="utf-8") as f:
print(f.read())
except FileNotFoundError:
print("No such file")
Output
No such file
Note
A relative name such as "students.txt" is looked for in the folder you ran Python from, which is not always the folder your script is in. If a file you can see "does not exist", that is usually why.
Why call strip() on each line read from a file?
Try this now
- Read marks.csv from the previous lesson, skip the header line, and print the average mark.
- Count the lines, words and characters in any text file, like the Unix wc command.
Create a free account to save your progress, or sign in.