Reading Files
Python's built-in open() function provides all you need to read files. Always use the with statement so the file is automatically closed.
Basic Read
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read() # entire file as one string
print(content)readlines() & readline()
with open("data.txt", "r", encoding="utf-8") as f:
lines = f.readlines() # list of strings (with \n)
print(lines[0])
with open("data.txt", "r", encoding="utf-8") as f:
first = f.readline() # one line at a timeIterating Line by Line (Memory Efficient)
with open("data.txt", "r", encoding="utf-8") as f:
for line in f: # best for large files
print(line.rstrip())with Statement Details
# Equivalent without with:
f = open("data.txt", "r")
try:
data = f.read()
finally:
f.close() # must close manuallyReading Binary Files
with open("image.png", "rb") as f:
header = f.read(8) # first 8 bytes
print(header)