繁体   English   中英

如何使用python恢复文件的读取操作

[英]how to resume read operation of file using python

我有一个15-16GB的文件,包含由新行分隔的json对象( \\ n )。

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

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

如果在读取读数时,我的脚本在5GB后失败,如何从上次读取位置恢复读取操作并从那里继续。

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

由于此文件包含json对象,因此在搜索操作之后会出现以下错误。

ValueError:无法解码JSON对象

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

我怎么解决这个问题? 有没有其他方法可以读取python中的最后一个读取位置。

使用其他文件存储当前位置:

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 
>>> 

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

for i in range(passed_variable):
    opened_file.readline()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM