Called with no argument, read() consumes everything from the file's current position to the end and returns it as one string, which is convenient for small files but can use a lot of memory for large ones, since the whole content is loaded at once. Passing an integer reads at most that many characters, or bytes in binary mode, and advances the file's position accordingly, so calling it repeatedly reads the file in chunks. Once read() reaches the end of the file, subsequent calls return an empty string.
1Understanding read()
Called with no argument, read() consumes everything from the file's current position to the end and returns it as one string, which is convenient for small files but can use a lot of memory for large ones, since the whole content is loaded at once. Passing an integer reads at most that many characters, or bytes in binary mode, and advances the file's position accordingly, so calling it repeatedly reads the file in chunks. Once read() reaches the end of the file, subsequent calls return an empty string.
For large files, read the file line by line (iterating over it directly, or with readline()) or in fixed-size chunks with read(size), instead of calling plain read() and loading the entire file into memory at once.
with open("notes.txt", "w") as f:
f.write("Line one\nLine two")
with open("notes.txt", "r") as f:
contents = f.read()
print(contents)2Practical Example
Here is a real-world application of read() showing how it is used in production Python code.
with open("notes.txt", "r") as f:
chunk = f.read(4)
print(repr(chunk))
print(repr(f.read(4)))3Best Practices
Follow these guidelines when working with read():
1. Use read() without arguments only for files you know are reasonably small
2. Read large files in chunks with read(size) or line by line to avoid loading everything into memory at once
3. Always open and read files inside a with block so the file is closed automatically afterward
Tip: For large files, read the file line by line (iterating over it directly, or with readline()) or in fixed-size chunks with read(size), instead of calling plain read() and loading the entire file into memory at once.
with open("notes.txt", "w") as f:
f.write("Line one\nLine two")
with open("notes.txt", "r") as f:
contents = f.read()
print(contents)