To read a file line by line in Python, you can use a
for loop or the
readline() method. Here's a detailed explanation of both approaches:
1. Using a
1 2 3 4 5 6 7
# Open the file with open('filename.txt', 'r') as file: # Iterate over each line in the file for line in file: # Process each line print(line)
In this approach, the
open() function is used to open the file in read mode ('r'). The file is automatically closed when the
with block is exited.
for loop iterates over each line in the file, assigning the current line to the variable
line. You can then process each line as desired. In the example above, each line is printed.
2. Using the
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Open the file file = open('filename.txt', 'r') # Read the first line line = file.readline() # Continue reading subsequent lines until the end of the file while line: # Process the line print(line) # Read the next line line = file.readline() # Close the file file.close()
In this approach, the file is opened using the
open() function. The file object is assigned to the variable
The first line of the file is read using the
readline() method and stored in the variable
readline() method reads a single line from the file, including the newline character at the end of the line.
while loop is then used to continue reading subsequent lines until the end of the file. Inside the loop, you can process each line as needed.
After reading all the lines, it's important to close the file using the
close() method to free up system resources.
Both methods allow you to read a file line by line in Python. Choose the approach that best suits your needs and the specific requirements of your program. Remember to handle any exceptions that may occur when working with files, such as