Python 如果转储失败,yaml 将写入空文件

Python yaml writes empty file if dump fails

我有以下片段:

if file:
    try:
        with open(file, 'w') as outfile:
            try:
                yaml.dump(self.dataset_configuration, outfile, default_flow_style=False)
                self.dataset_configuration_file = file
            except yaml.YAMLError as ex:
                _logger.error("An error has occurred while trying to save dataset configuration:\n", ex)
    except OSError as ex:
        _logger.error(f"Unable to create file '{self.dataset_configuration_file}' "
                      f"to persist the dataset configuration\n", ex)

我注意到有时候,如果对象不能是 picked/serialized,那么 dump 方法会失败并写入一个空文件。如果打开的文件已经存在,是否有一个快速选项可以不覆盖它,或者我是否必须复制该文件,然后如果 dump 操作失败,我会恢复文件?

以上根据@martineau的建议,也可以改写为:

if file:
    serialized_object_string = ''
    try:
        serialized_object_string = yaml.dump(self.dataset_configuration, default_flow_style=False)
    except yaml.YAMLError as ex:
        _logger.error("An error has occurred while trying to save dataset configuration:\n", ex)
    if serialized_object_string:
        try:
            with open(file, 'w') as output_file:
                output_file.write(serialized_object_string)
                self.dataset_configuration_file = file
        except OSError as ex:
            _logger.error(f"Unable to create file '{self.dataset_configuration_file}' "
                          f"to persist the dataset configuration\n", ex)

在这种情况下,首先将创建对象的字符串表示形式,然后如果它不为空或序列化失败,则将其写入文件。不通过 Stream 对象会受到重大惩罚吗?如果字符串表示非常大会怎样?有没有一种“本机”方法可以在一次操作中完成上述操作?

以上根据@martineau的建议,也可以改写为:

if file:
    serialized_object_string = ''
    try:
        serialized_object_string = yaml.dump(self.dataset_configuration, default_flow_style=False)
    except yaml.YAMLError as ex:
        _logger.error("An error has occurred while trying to save dataset configuration:\n", ex)
    if serialized_object_string:
        try:
            with open(file, 'w') as output_file:
                output_file.write(serialized_object_string)
                self.dataset_configuration_file = file
        except OSError as ex:
            _logger.error(f"Unable to create file '{self.dataset_configuration_file}' "
                          f"to persist the dataset configuration\n", ex)

虽然我希望有更多的“集成”解决方案,但它确实有效。