Reading a file line-by-line

suggest change

The simplest way to iterate over a file line-by-line:

with open('myfile.txt', 'r') as fp:
    for line in fp:
        print(line)

readline() allows for more granular control over line-by-line iteration. The example below is equivalent to the one above:

with open('myfile.txt', 'r') as fp:
    while True:
        cur_line = fp.readline()
        # If the result is an empty string
        if cur_line == '':
            # We have reached the end of the file
            break
        print(cur_line)

Using the for loop iterator and readline() together is considered bad practice.

More commonly, the readlines() method is used to store an iterable collection of the file’s lines. readlines() keeps the line endings, so rstrip removes them before printing. If myfile.txt contains hello and world on separate lines:

with open("myfile.txt", "r") as fp:
    lines = fp.readlines()
for i in range(len(lines)):
    print("Line " + str(i) + ": " + lines[i].rstrip("\n"))

This prints:

Line 0: hello Line 1: world

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents