How can Python read specific lines from a file?

You can use the linecache module to read specific lines from a file. Here is an example:

import linecache

def read_line(filename, line_number):
    line = linecache.getline(filename, line_number)
    return line.strip()

filename = "example.txt"
line_number = 5
line = read_line(filename, line_number)
print(f"Line {line_number}: {line}")

In the example above, the read_line function reads the specified line number from the file and returns its content. You just need to pass the file name and line number as parameters to the read_line function.

Please note that the linecache module caches every line of a file, so it may use a lot of memory when reading large files. If you need to read specific lines from a large file, consider using alternative methods like reading line by line and skipping unnecessary lines.

bannerAds