Python read() and readlines(): Read a Whole File
To read a whole file in Python, call read() for one string or readlines() for a list of lines.
Read Reading Text Files first. Each example starts with setup code that writes a small file with "w" mode, so it runs on its own; Writing text files explains it. The examples use tiny files and leave out very large files and binary data.
Read all the text with read()
read() returns the whole file as one string, newlines included.
with open("lesson-notes.txt", "w", encoding="utf-8") as fixture:
fixture.write("Ada\nSam\n")
with open("lesson-notes.txt", "r", encoding="utf-8") as source:
text = source.read()
print(repr(text))
print(text, end="")
repr() shows the hidden \n characters. text stays usable after the with block closes the file.
Get a list of lines
readlines() keeps each line's newline. read().splitlines() drops them. Use the loop from the prerequisite lesson for large files, because both of these hold the whole file in memory.
with open("lesson-notes.txt", "w", encoding="utf-8") as fixture:
fixture.write("Ada\nSam\n")
with open("lesson-notes.txt", "r", encoding="utf-8") as source:
print(source.readlines())
with open("lesson-notes.txt", "r", encoding="utf-8") as source:
print(source.read().splitlines())
This prints ['Ada\n', 'Sam\n'], then ['Ada', 'Sam'].
Note: an open file reads forward only. A second read() on the same file object returns "".
Empty and missing files
An empty file reads as "", so a loop over it runs zero times. A missing file raises FileNotFoundError at open().
with open("lesson-empty.txt", "w", encoding="utf-8") as fixture:
fixture.write("")
with open("lesson-empty.txt", "r", encoding="utf-8") as source:
print(repr(source.read()))
try:
with open("lesson-no-such-file.txt", "r", encoding="utf-8") as source:
print(source.read())
except FileNotFoundError:
print("File not found")
This prints '', then File not found. A relative filename is looked up in the program's working directory. In the browser that is temporary storage, not your own files.
Why encoding matters
encoding="utf-8" tells Python how bytes become characters. Without it, Python uses the system default, which differs between computers. A file with accents or emoji can then read wrongly or raise UnicodeDecodeError.
with open("lesson-cafe.txt", "w", encoding="utf-8") as fixture:
fixture.write("café\n")
with open("lesson-cafe.txt", "r", encoding="utf-8") as source:
print(source.read(), end="")
with open("lesson-cafe.txt", "r", encoding="latin-1") as source:
print(source.read(), end="")
The second line prints café: the right bytes, decoded with the wrong encoding.
See also: Writing text files, JSON.
Your turn
Read path with read().splitlines(), then print how many lines it has and the last line. If the file is missing, print File not found instead.
path = "lesson-whole-task.txt"
with open(path, "w", encoding="utf-8") as fixture:
fixture.write("Mia\nLeo\nZara\n")
# add a try block: read path into a list of lines, print its length and last item
# add an except FileNotFoundError block that prints File not found
Expected output
3
Zara