Python json.dump生成大小为零字节的文件

问题描述 投票:1回答:1

在我的代码的某个阶段,我需要将python字典转储到json文件中。这是执行此操作的代码:

def output_batch(self, batch):
    with open(os.path.join(self.get_current_job_directory(), 'batch_' + str(self.index) + '.json'), 'w') as json_file:
        json.dump(batch, json_file, sort_keys = True, indent = 4, separators = (',', ': '))
    exit()

这里self.index是一个唯一的整数索引,用于标识此特定实例。 self.get_current_job_directory()返回应该创建文件的路径。

在转储之前记录字典的长度会返回42691。但是输出文件的大小为零字节。这没有任何意义。即使在空dict的情况下,文件也将是2个字节长(以补偿{})。

代码是高度并行化的map-reduce样式管道的一部分,几乎不可能在这里重现。现在有一百万件事可能在这样的设置中出错,但没有其他线程可以访问被转储的dict,没有其他线程可以访问相同的输出文件。

***更新:在此函数调用之后,进程退出(通过调用exit()),可能与此有关吗?

关于为什么会发生这种情况的任何建议或想法?

python json dictionary
1个回答
1
投票

可能是with上下文在函数结束时没有正确退出。尝试显式关闭文件。

def output_batch(self, batch):
    json_file = open(...):
    json.dump(batch, json_file, sort_keys = True, indent = 4, separators = (',', ': '))
    json_file.close()

此外,请确保您使用写入权限调用open('w'),并且您有权写入该位置。

© www.soinside.com 2019 - 2024. All rights reserved.