Reading Files
Python provides three different methods to read file content, each suited for different situations.
Method 1: read() — Read Everything At Once
file = open("sample.txt", "r")
content = file.read()
print(content)
file.close() # Always close the file
This loads the entire file into memory as a single string. Works great for small files, but can crash your program if the file is very large (e.g., a 2 GB log file).
Method 2: readline() — Read One Line At A Time
file = open("sample.txt", "r")
first_line = file.readline()
second_line = file.readline()
print(first_line)
print(second_line)
file.close()
Each call to readline() moves the cursor to the next line, like reading a book one sentence at a time.
Method 3: readlines() — Read All Lines Into A List
file = open("sample.txt", "r")
all_lines = file.readlines()
print(all_lines) # Output: ['Line 1\n', 'Line 2\n', 'Line 3\n']
file.close()
Returns a list where each element is one line from the file. Notice that each line keeps the \n newline character at the end.
The with Statement (Recommended Way)
Forgetting file.close() is one of the most common beginner mistakes. The with statement solves this — Python automatically closes the file when the block ends, even if an error occurs:
with open("sample.txt", "r") as file:
content = file.read()
print(content)
# File is automatically closed here — no need to call file.close()
Always use the with statement when working with files. It is safer and cleaner than manually calling file.close().
Reading Line-by-Line with a for Loop
For large files, the most memory-efficient approach is to loop through the file object directly:
with open("server_log.txt", "r") as file:
for line in file:
print(line.strip()) # strip() removes the trailing \n
This reads only one line at a time into memory, even if the file has millions of lines.
Quick Summary
- Context Manager (
with open(...) as f:): The standard Python best practice that automatically closes the file upon exit. file.read(): Reads the entire file content into a single string in memory.file.readline(): Reads one line at a time from current cursor position.file.readlines(): Loads all lines as a list of strings.- Streaming Line-by-Line:
for line in file:streams large multi-gigabyte files efficiently without RAM exhaustion.
What's Next?
Let's look at how to write new files and append text to existing logs in Writing & Appending Files!