In this Python tutorial, we will learn, how to read a file line by line in Python with a few examples.
There are five methods to read a file line by line in Python, which are shown below:
- Using for loop
- Using readline()
- Using readlines() method
- Using a For Loop and List Comprehension
- Using the iter() with the next() Function
Python read a file line by line
Reading a file line by line is a common task in many Python programs, especially those that deal with large files. There are several methods that can be used to read a file line by line in Python.
Method-1: Python read a file line by line using for loop
This is the simplest method to read a file line by line in Python. It uses a for loop to iterate through the file object, which automatically reads the file one line at a time. This method is easy to understand and use, and it’s a good choice if you just need to process each line of the file one by one.
Open any text editor and write the lines as shown in the above picture and save the file with an extension (.txt). Now use the below code to read the file line by line.
# Open a file named 'python.txt' using a 'with' statement to ensure it's properly closed
with open('python.txt') as f:
# Iterate over each line in the file and print it to the console
for line in f:
print(line)
The above code opens a file named ‘python.txt’ and reads its content line by line.
- It does so using the built-in ‘open’ function in Python, with a ‘with’ statement to ensure that the file is properly closed when the block is exited.
- The code then iterates over each line in the file using a ‘for’ loop and prints each line to the console using the ‘print’ function.
Read: Get current directory Python
Method-2: Python read a file line by line using readline()
This method reads each line of the file using the readline() method, which returns a single line of the file at a time. The method then uses a while loop to process each line until the readline() method returns an empty string, indicating the end of the file.
# Open a file named 'python.txt' in read mode using a 'with' statement
with open('python.txt', 'r') as file:
# Read the first line of the file
line = file.readline()
# Continue reading the file line by line using a 'while' loop
while line:
line = file.readline()
# Print each line to the console
print(line)
The above code opens a file named ‘python.txt’ in read mode and reads its content line by line.
- It does so using the built-in ‘open’ function in Python, with a ‘with’ statement to ensure that the file is properly closed when the block is exited.
- The code then reads the first line of the file using the ‘readline’ method and enters a ‘while’ loop that continues to read the file line by line until it reaches the end. For each line, the code prints it to the console using the ‘print’ function.
Read: Python copy file
Method-3: Python read a file line by line using readlines() method
This method reads the entire file into a list of strings using the readlines()
method.
# Define a list of strings
Line = ["Welcome\n","to\n","Pythonguides\n"]
# Open a file named 'line.txt' in write mode
file = open('line.txt', 'w')
# Write the strings from the list to the file using the 'writelines' method
file.writelines(Line)
# Close the file
file.close()
# Re-open the file in read mode
file = open('line.txt', 'r')
# Read the contents of the file into a list of strings
Lines = file.readlines()
# Iterate over the list of strings and print each one to the console
for line in Lines:
print(line)
The above code creates a list of strings and writes its contents to a file named ‘line.txt’ using the built-in ‘open’ function in Python.
- It writes the strings from the list to the file using the ‘writelines’ method and then closes the file.
- The code then reopens the file in read mode, reads its contents into a list of strings using the ‘readlines’ method, and iterates over the list to print each line to the console using the ‘print’ function.
Read: Python Count Words in File
Method-4: Python read a file line by line using a For Loop and List Comprehension
This method reads the entire file into a list of stripped strings using a combination of a for loop and list comprehension. The for loop is used to iterate through the file object and the list comprehension is used to create a new list of stripped lines.
# Open a file named 'python.txt' in read mode using a 'with' statement
with open('python.txt', 'r') as file:
# Read the contents of the file into a list of strings using a list comprehension
lines = [line.strip() for line in file]
The above code opens a file named ‘python.txt’ in read mode using a ‘with’ statement.
- It then reads the contents of the file into a list of strings using list comprehension. The ‘strip’ method is used to remove any leading or trailing whitespace from each line in the file.
- The resulting list contains one string element for each line in the file, with the strings separated by ‘\n’ characters.
Read: PdfFileWriter Python Examples
Method-5: Python read a file line by line using the iter() with the next() Function
This method uses the iter() function to create an iterator object from the file object and then uses the next() function to read each line of the file one at a time. You can use a while loop to read each line of the file until the end of the file is reached.
# Open a file named 'python.txt' in read mode using a 'with' statement to ensure it's properly closed
with open('python.txt', 'r') as file:
# Create an iterator over the file's lines
lines = iter(file)
# Loop over the iterator until there are no more lines to read
while True:
try:
# Get the next line from the iterator and print it after removing any leading or trailing whitespace
line = next(lines)
print(line.strip())
except StopIteration:
# Exit the loop when there are no more lines to read
break
The above code opens a file in read mode, creates an iterator over the file’s lines, and loops over the iterator to read and print each line of the file after removing any leading or trailing whitespace. The ‘with’ statement ensures that the file is properly closed when the block is exited.
You may also like to read the following Python tutorials.
Conclusion
In this tutorial, we have learned about Python read a file line by line example, and also we have covered these methods:
- Using for loop
- Using readline()
- Using readlines() method
- Using a For Loop and List Comprehension
- Using the iter() with the next() Function
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.