Home >Backend Development >Python Tutorial >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()
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
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!