【问题标题】:Canceling the Python process while reading a file corrupts the file在读取文件时取消 Python 进程会损坏文件
【发布时间】:2020-12-29 18:25:14
【问题描述】:

我有一个简单的过程,可以将项目读取和写入文件。有时,如果我在读取过程中终止 Python 进程(控制台中的“Ctrl c”),文件会损坏并且无法再读取。我怎样才能防止这种情况?我已经将“rb”作为打开模式。也许我可以确保python在文件打开例程中不会取消?

代码如下:

    import dill
    results = []
    with open(self.getFile(), 'rb') as input:
        if n is not None:
            for i in range(n):
                try:
                    results.append(dill.load(input))
                except (EOFError, pickle.UnpicklingError) as e:
                    print('ERROR with reading {}'.format(self.getFile()))
                    pass

为了完整起见,还有写作过程——希望是无关紧要的。

def write(self, objects):
    with open(self.getFile(), 'wb') as output:
        for object in objects:
            dill.dump(object, output, pickle.HIGHEST_PROTOCOL)

问题又发生了,现在我可以看到完整的错误:

    results.append(dill.load(input))
  File "/home/x/anaconda3/envs/myenv3/lib/python3.6/site-packages/dill/_dill.py", line 270, in load
    return Unpickler(file, ignore=ignore, **kwds).load()
  File "/home/x/anaconda3/envs/myenv3/lib/python3.6/site-packages/dill/_dill.py", line 472, in load
    obj = StockUnpickler.load(self)
EOFError: Ran out of input

【问题讨论】:

  • 去掉try-except或者使用"traceback.print_exc()"查看实际错误
  • 为了使文件损坏,需要将其写入。读取它永远不会改变它的内容。 Something 将不完整的数据写入该文件。 write 是否可能同时执行?
  • 本身不相关,但您在代码中使用了一些保留关键字 - objectinput 是您不应该使用的内置名称。

标签: python file dill


【解决方案1】:

您面临的问题是由于您试图在单个文件中转储和加载多个对象,这是不允许的。不允许我的意思是它们可以存在于列表和字典中,但不能作为单独的对象存在。所以这里的解决方案是使用列表来存储和检索对象。

这是你修改过的写函数

def write(self, objects):
    with open(self.getFile(), 'wb') as output:
        dill.dump(objects, output, pickle.HIGHEST_PROTOCOL)

同样的方式是你读取函数

    import dill
    with open(self.getFile(), 'rb') as input:
        results = dill.load(input)

也正如@Random_Davis 所说,最好不要使用内置对象名称作为参数或变量。

【讨论】:

    猜你喜欢
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 2020-12-16
    相关资源
    最近更新 更多