How do I read a file line by line in Python?
Davide S
davide s profile pic

To read a file line by line in Python, you can use afor loop or thereadline() method. Here's a detailed explanation of both approaches: 1. Using afor loop:

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, theopen() function is used to open the file in read mode ('r'). The file is automatically closed when thewith block is exited. Thefor loop iterates over each line in the file, assigning the current line to the variableline. You can then process each line as desired. In the example above, each line is printed. 2. Using thereadline() method:

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 theopen() function. The file object is assigned to the variablefile. The first line of the file is read using thereadline() method and stored in the variableline. Thereadline() method reads a single line from the file, including the newline character at the end of the line. Awhile 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 theclose() 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 asFileNotFoundError orIOError.