Skip to main content
 首页 » 编程设计

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

2024年09月07日14unruledboy

在我的代码的某个阶段,我需要将 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。但是,输出文件的大小为零字节。这真的没有任何意义。即使是空字典,文件也有 2 个字节长(以补偿 {})。

该代码是高度并行化的 map-reduce 风格管道的一部分,几乎不可能在此处重现。现在在这样的设置中有一百万个可能出错的地方,但是没有其他线程可以访问正在转储的 dict 并且没有其他线程可以访问相同的输出文件。

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

关于为什么会发生这种情况有什么建议或想法吗?

请您参考如下方法:

可能是 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'),并且您有权写入该位置。