Python

How to read a file line by line in Python?

Reading a file line by line is a common task in Python, especially when dealing with large datasets or log files. In this guide, we'll explore simple and effective ways to read a file line by line using Python.


Using a For Loop:

 
# Open the file in read mode
with open('filename.txt', 'r') as file:
# Iterate through each line in the file
for line in file:
# Process each line as needed
print(line.strip()) # Example: Print each line (stripping newline characters)

This method is memory-efficient, as it reads one line at a time and doesn't load the entire file into memory.


Using readlines():

 
# Open the file in read mode
with open('filename.txt', 'r') as file:
  # Read all lines into a list
   lines = file.readlines()
# Iterate through the list
for line in lines: print(line.strip()) # Example: Print each line (stripping newline characters)

While readlines() reads all lines at once, it can be useful if you need to access lines randomly. However, it's less memory-efficient for large files.


Using readline():

 
# Open the file in read mode
with open('filename.txt', 'r') as file:
# Read the first line
line = file.readline()
# Continue reading one line at a time
while line: print(line.strip())
# Example: Print each line (stripping newline characters)
line = file.readline()

This method reads one line at a time and is useful when you want more control over the reading process.


Conclusion:

Reading a file line by line in Python is a straightforward process with multiple approaches. Choose the method that best fits your specific needs, whether it's for memory efficiency, random access, or fine-tuned control over the reading process.

By following these examples, you can easily incorporate file reading into your Python scripts for effective data processing.

  • Leave Comment about this Article

    Rating

review

0 Comments