Home >Backend Development >Python Tutorial >How to Efficiently Read Specific Lines from a Large File in Python?
Reading Specific Lines from a File
When iterating through a file using a for loop, it may be necessary to read only specific lines. In Python, while one can use a loop to iterate over all lines in a file, there is no built-in feature to read specific lines without reading the entire file.
However, a workaround is available for situations where the file is large and reading the entire file into memory is not feasible. This involves iterating through the file line by line and applying a condition to read the desired lines:
fp = open("file") for i, line in enumerate(fp): if i == 25: # Process 26th line elif i == 29: # Process 30th line elif i > 29: break fp.close()
Note: The line number in the loop is zero-based, meaning the first line has an index of 0.
Python 2.6 and Later:
In Python 2.6 and later, you can leverage the with statement to ensure proper file handling:
with open("file") as fp: for i, line in enumerate(fp): if i == 25: # Process 26th line elif i == 29: # Process 30th line elif i > 29: break
The above is the detailed content of How to Efficiently Read Specific Lines from a Large File in Python?. For more information, please follow other related articles on the PHP Chinese website!