我正在处理一个非常大的文本文件(tsv),大约有2亿个条目。其中一列是date,记录按date排序。现在,我想开始读取给定日期的记录。目前我只是从头开始阅读,速度非常慢,因为我需要阅读近100-1.5亿条记录才能达到这个记录。我在想,如果我可以使用二进制搜索来加快速度,我可以在最多28次额外的记录读取(log(2亿))。python允许读取第n行而不缓存或读取之前的行吗?
发布于 2015-06-30 04:13:32
您可以使用fileObject.seek(offset[, whence])方法
#offset -- This is the position of the read/write pointer within the file.
#whence -- This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end.
file = open("test.txt", "r")
line_size = 8 # Because there are 6 numbers and the newline
line_number = 5
file.seek(line_number * line_size, 0)
for i in range(5):
print(file.readline())
file.close()对于这段代码,我使用了下面的文件:
100101
101102
102103
103104
104105
105106
106107
107108
108109
109110
110111https://stackoverflow.com/questions/31124088
复制相似问题