我正在读取文本文件中的特定行。这是我的代码:
file.seek(0)
for j, ln in enumerate(file):
if j == line_number
line = ln # i'm getting the line
break
当我在“循环”中使用此代码时,花费了很长的时间,其中 line_number 每回合都是随机的。 我也试过 linecache.getline() 但它需要每次都调用 linecache.clearcache() ,所以它不是更好。
是否有更快的解决方案?内存无关紧要。
最佳答案
如果内存真的无关紧要:
lines = file.readlines()
line = lines[line_number]
您一次读取文件,将其存储在内存中,然后从那里访问它。
编辑:内存重要的地方:
from itertools import dropwhile
line = next(dropwhile(lambda x: x[0]==line_number, enumerate(file)))[1]
我们可以使用 itertools.dropwhile()
忽略这些行,直到找到我们需要的行。
关于python - 循环读取文件中的特定行(优化),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10439368/