Open a text file, read it all at once, line by line or a few characters at a time, and close it again.
First line
Second line
Third line
Three lines. Each ends with a newline character \n, drawn as ↵ in the pictures.
An open file remembers where it is. Every read starts at the cursor and moves it forward.
# open and read file
file = open("data.txt", "r")
content = file.read()
file.close()
# with statement
with open("data.txt", "r") as file:
content = file.read()
# ans: file automatically closed
The file closes when the indented block ends, even if an error happens inside it.
# read all lines
with open("data.txt", "r") as file:
lines = file.readlines()
# ans: returns list of lines
# iterate over lines
with open("data.txt", "r") as file:
for line in file:
print(line.strip())
Only one line is in memory at a time, so this works for files of any size.
# read one line at a time
with open("data.txt", "r") as file:
line1 = file.readline()
line2 = file.readline()
# read n characters
with open("data.txt", "r") as file:
content = file.read(10)
# ans: first 10 characters
Predict, then reveal. Watch the cursor.
# what happens without close?
file = open("data.txt", "r")
content = file.read()
# ans: file remains open (bad practice)
# read() returns what type?
with open("data.txt", "r") as f:
content = f.read()
# ans: str (string)
# readlines() returns?
with open("data.txt", "r") as f:
lines = f.readlines()
# ans: list of strings
# strip() in loop?
for line in file:
print(line.strip())
# ans: removes \n at end
# read empty file?
with open("empty.txt", "r") as f:
content = f.read()
# ans: "" (empty string)
# file not found?
with open("missing.txt", "r") as f:
pass
# ans: FileNotFoundError
# read twice?
with open("data.txt", "r") as f:
c1 = f.read()
c2 = f.read()
# ans: c2 is "" (already at end)
# readline at end?
with open("data.txt", "r") as f:
f.read()
line = f.readline()
# ans: "" (empty string)
# iterate multiple times?
with open("data.txt", "r") as f:
for line in f:
pass
for line in f:
pass
# ans: second loop doesn't run
Call f.seek(0) to move the cursor back to the start before reading again.
# read with encoding?
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read()
# ans: specify encoding explicitly
Without it, Python uses the system's default encoding, which differs between computers.
with open(...)Closes the file for you. Without it, call close() yourself.
read() one string, read(n) n characters, readline() one line, readlines() a list.
for line in file reads one line at a time; strip() removes the \n.
At the end, reads return "" and loops do nothing, until you seek(0).