Wednesday, January 15, 2025
HomeTechRead a file line by line in Python

Read a file line by line in Python

Reading a file line by line in Python is straightforward and can be done using various methods. Below are some common approaches:

1. Using a for Loop

This is the most Pythonic way to read a file line by line.

python
with open('filename.txt', 'r') as file:
for line in file:
print(line.strip()) # `strip()` removes leading/trailing whitespace

2. Using readline()

The readline() method reads one line at a time. You can use it in a loop.

python
with open('filename.txt', 'r') as file:
line = file.readline()
while line:
print(line.strip())
line = file.readline()

3. Using readlines()

The readlines() method reads all lines at once and returns them as a list. This can be useful for smaller files.

python
with open('filename.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line.strip())

4. Using fileinput (for Multiple Files)

The fileinput module allows you to read from multiple files line by line.

python
import fileinput

for line in fileinput.input(files=('file1.txt', 'file2.txt')):
print(line.strip())

5. Efficient Reading for Large Files

For large files, reading line by line (using a for loop) is memory efficient because it doesn’t load the entire file into memory.

python
with open('largefile.txt', 'r') as file:
for line in file:
process(line) # Replace `process` with your function

Notes:

  • Always use with open() to handle files, as it ensures the file is properly closed after use.
  • Use strip() to remove newline characters (\n) or extra spaces at the ends of lines.
  • Replace 'filename.txt' with the path to your file.
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x