Python File Reading
Python lets you read files using built-in methods provided by the open()
function. Reading from files is essential for working with logs, configuration files, text data, and more.
Let’s assume we have a file named example.txt
with the following content:
example.txt
Hello World
Welcome to Python
This is a file.
1. Open and Read Entire File
f = open("example.txt", "r")
print(f.read())
f.close()
Output:
Hello World
Welcome to Python
This is a file.
Explanation:
open("example.txt", "r")
: Opens the file in read mode.f.read()
: Reads the entire content of the file as one string.f.close()
: Always close the file after reading to free system resources.
2. Using with
(Best Practice)
with open("example.txt", "r") as f:
content = f.read()
print(content)
Output:
Hello World
Welcome to Python
This is a file.
Explanation:
with
: Manages the file context automatically (closes the file even if errors occur).f.read()
: Same as before, reads the whole file at once.- No need to call
f.close()
—it's done for you!
3. Read First N Characters
with open("example.txt", "r") as f:
print(f.read(5))
Output:
Hello
Explanation:
f.read(5)
: Reads the first 5 characters of the file, useful for preview or parsing headers.
4. Read One Line at a Time
with open("example.txt", "r") as f:
line = f.readline()
print(line)
Output:
Hello World
Explanation:
f.readline()
: Reads just one line from the file (including the\n
newline character if present).
5. Read All Lines as a List
with open("example.txt", "r") as f:
lines = f.readlines()
print(lines)
Output:
['Hello World\n', 'Welcome to Python\n', 'This is a file.\n']
Explanation:
f.readlines()
: Returns a list of all lines, each line is a string ending with\n
.
6. Read File Line by Line (Loop)
with open("example.txt", "r") as f:
for line in f:
print(line.strip())
Output:
Hello World
Welcome to Python
This is a file.
Explanation:
- Looping over the file reads each line one by one.
line.strip()
removes\n
and any extra whitespace.
✅ Why it's good:
Efficient for large files; you don’t load everything into memory at once.
7. Read Large File Efficiently (Generator)
def read_large_file(filename):
with open(filename, "r") as f:
for line in f:
yield line.strip()
for line in read_large_file("example.txt"):
print(line)
Output:
Hello World
Welcome to Python
This is a file.
Explanation:
yield
: Makes this a generator, useful when working with large files.- Reads line-by-line without storing the entire file in memory.
8. Handle File Not Found
try:
with open("notfound.txt", "r") as f:
print(f.read())
except FileNotFoundError:
print("File not found.")
Output:
File not found.
Explanation:
- Wraps file opening in a
try-except
block. FileNotFoundError
: Catches the error if the file doesn’t exist.
9. Count Total Lines in File
with open("example.txt", "r") as f:
count = sum(1 for _ in f)
print("Total lines:", count)
Output:
Total lines: 3
Explanation:
- Counts the number of lines using a generator expression.
sum(1 for _)
: Adds 1 for each line.
Summary Table
Function | Description |
---|---|
read() | Read entire content as one string |
read(n) | Read first n characters |
readline() | Read one line at a time |
readlines() | Return a list of all lines |
for line in f | Efficient way to read line-by-line |