Python - Read file at specific lines

By xngo on July 26, 2019

In Python, there are multiple ways to read file at specific lines. Some are convenient for small files and some are better for big files. In this tutorial, I will show you ways to read files at specific lines for small and big files.

Small file

For small file, you can load the whole file into memory and access specific lines directly by using the indices. Here are the examples to print the 26th and 30th lines.

# Load the whole file into memory.
with open("myfile.txt", "r") as file:            
    lines=file.readlines()
 
# Print the 26th and 30th lines.
print(lines[25])
print(lines[29])

Or, you can use linecache as follows.

import linecache
print(linecache.getline("myfile.txt", 26))
print(linecache.getline("myfile.txt", 30))

Big file

For big file, it is better to iterate through each line of the file and then process at specific line. In this way, you will not run out of memory and you don't have to read through the whole file. As a matter of fact, this way of reading the file is more efficient than what are being shown above. Here is an example.

with open("myfile.txt", "r") as file:
    for i, line in enumerate(file):
        if i == 25:
            print(line) # 26th line
        elif i == 29:
            print(line) # 30th line
        elif i > 29:
            break

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.