Home > Backend Development > Python Tutorial > How Can I Efficiently Read Specific Lines from a Large File in Python?

How Can I Efficiently Read Specific Lines from a Large File in Python?

Mary-Kate Olsen
Release: 2024-12-10 03:18:13
Original
987 people have browsed it

How Can I Efficiently Read Specific Lines from a Large File in Python?

Line-Specific File Reading in Python

When processing large text files, it's often necessary to read only specific lines rather than the entire file. This can optimize performance and save memory. Python offers ways to achieve this without loading the complete file into memory.

Reading Specific Lines Using Line Number

Suppose you want to read line 26 and line 30 from a large text file. A straightforward approach is to open the file and use a for loop to iterate over the lines:

fp = open("file")
for i, line in enumerate(fp):
    if i == 25:
        # 26th line
    elif i == 29:
        # 30th line
    elif i > 29:
        break
fp.close()
Copy after login

Note that i == n - 1 for the nth line. This allows you to specify the desired line numbers precisely.

Alternatively, if you're using Python 2.6 or later, you can use the following syntax:

with open("file") as fp:
    for i, line in enumerate(fp):
        if i == 25:
            # 26th line
        elif i == 29:
            # 30th line
        elif i > 29:
            break
Copy after login

This approach automatically handles file closing and is more concise.

The above is the detailed content of How Can I Efficiently Read Specific Lines from a Large File in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template