3

我有一个大小为 15-16GB 的文件,其中包含由换行符 ( \n ) 分隔的 json 对象。

我是 python 新手并使用以下代码读取文件。

with open(filename,'rb') as file:
  for data in file:  
    dosomething(data)

如果在阅读阅读时,我的脚本在 5GB 后失败,我如何从最后一个阅读位置恢复阅读操作并从那里继续。

我试图通过使用 file.tell() 来获取位置并使用 seek() 函数移动指针来做同样的事情。

由于此文件包含 json 对象,因此在查找操作后出现以下错误。

ValueError:无法解码任何 JSON 对象

我假设在查找操作之后指针没有得到正确的 json。

我该如何解决这个问题?有没有其他方法可以从 python 中的最后读取位置读取。

4

2 回答 2

2

使用另一个文件来存储当前位置:

cur_loc = open("location.txt", "w+")
cur_loc.write('0')
exception = False

i = 0

with open("test.txt","r") as f:
    while(True):
        i+=1
        if exception:
            cur_loc.seek(0)
            pos = int(cur_loc.readline())
            f.seek(pos)
            exception = False

        try:
            read = f.readline()
            print read,
            if i==5:
                print "Exception Happened while reading file!"
                x = 1/0 #to make an exception
            #remove above if block and do everything you want here.
            if read == '':
                break
        except:
            exception = True
            cur_loc.seek(0)
            cur_loc.write(str(f.tell()))

cur_loc.close()

假设我们有以下text.txt作为输入文件:

#contents of text.txt
1
2
3
4
5
6
7
8
9
10

当您运行上述程序时,您将拥有:

>>> ================================ RESTART ================================
>>> 
1
2
3
4
5
Exception Happened while reading file!
6
7
8
9
10 
>>> 
于 2016-04-27T09:44:27.590 回答
0

您可以使用 for i, line in enumerate(opened_file) 来获取行号并存储此变量。当您的脚本失败时,您可以向用户显示此变量。然后,您需要为此变量创建一个可选的命令行参数。如果给定变量,您的脚本需要为范围(变量)中的 i 执行 opens_file.readline()。这样你就会到达你离开的地方。

for i in range(passed_variable):
    opened_file.readline()
于 2016-04-27T09:38:39.057 回答