你说你有“大约 500GB 的文本文件”。如果我理解正确,则每次观察都没有固定的长度(注意,我不是在谈论行数,我指的是观察的所有行的总长度,以字节为单位)。这意味着您将不得不浏览整个文件,因为您无法确切知道换行符的位置。
现在,根据每个单独的文本文件的大小,您可能需要寻找不同的答案。但是如果每个文件都足够小(小于 1 GB?),您也许可以使用该linecache
模块,它会为您处理逐行查找。
您可能会像这样使用它:
import linecache
filename = 'observations1.txt'
# Start at 44th line
curline = 44
lines = []
# Keep looping until no return string is found
# getline() never throws errors, but returns an empty string ''
# if the line wasn't found (if the line was actually empty, it would have
# returned the newline character '\n')
while linecache.getline(filename, curline):
for i in xrange(75):
lines.append(linecache.getline(filename, curline).rstrip())
curline += 1
# Perform work with the set of observation lines
add_to_observation_log(lines)
# Skip the unnecessary section and reset the lines list
curline += 4
lines = []
我对此进行了测试,它在五秒钟内浏览了一个 23MB 的文件。