从命令行查找文件中特定行的字节位置的最快方法是什么?
例如
$ linepos myfile.txt 13
5283
我正在为大小为几 GB 的 CSV 编写解析器,如果解析器停止,我希望能够从上一个位置恢复。解析器在 Python 中,但即使遍历 file.readlines()
也需要很长时间,因为文件中有数百万行。我想简单地执行 file.seek(int(command.getoutput("linepos myfile.txt %i"% lastrow)))
,但我找不到有效执行的 shell 命令这个。
编辑:很抱歉造成混淆,但我正在寻找非 Python 解决方案。我已经知道如何通过 Python 执行此操作。
最佳答案
来自@chepner 对我的另一个回答的评论:
position = 0 # or wherever you left off last time
try:
with open('myfile.txt') as file:
file.seek(position) # zero in base case
for line in file:
position = file.tell() # current seek position in file
# process the line
except:
print 'exception occurred at position {}'.format(position)
raise
关于linux - 如何找到文件中特定行的字节位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21559181/