6.3 File Reading Methods
We explore the read(), readline(), and readlines() methods for reading content from files, as well as the efficient way to iterate over a file object.
Python offers several methods for reading data from a file opened in read mode. The choice of the appropriate method depends on the file size and how you want to process the data.
- `read(size)`: Reads and returns the file content as a single string. Optionally, you can provide a `size` argument to read a specific number of bytes. Caution: Using `read()` without an argument on very large files can consume all of your system's RAM.
- `readline()`: Reads a single line from the file, from the current position to the next newline character (`\n`). It is useful when you want to process a file line-by-line manually.
- `readlines()`: Reads all lines of the file and returns them as a list of strings. Each list item corresponds to a line in the file and includes the newline character (`\n`). Like `read()`, it can be problematic for very large files.
Tip!
The recommended way to read: `for line in file_object`. This is the most efficient and "Pythonic" way to read a file line-by-line. It does not load the entire file into memory at once, making it ideal for processing large files.
# Create a file for the examples
with open("reading_example.txt", "w", encoding="utf-8") as f:
f.write("Line 1\n")
f.write("Line 2\n")
f.write("Line 3\n")
# 1. read()
with open("reading_example.txt", "r", encoding="utf-8") as f:
print("With read():\n" + f.read())
# 2. readlines()
with open("reading_example.txt", "r", encoding="utf-8") as f:
lines_list = f.readlines()
print("With readlines():\n", lines_list)
# 3. Iteration (loop)
with open("reading_example.txt", "r", encoding="utf-8") as f:
print("With iteration:")
for i, line in enumerate(f):
print(f" Line {i+1}: {line.strip()}")
Explore More with AI
Use AI to generate new examples, delve deeper into theory, or get your questions answered.