【问题标题】:Writing yaml file: attribute error编写yaml文件:属性错误
【发布时间】:2018-01-17 09:51:14
【问题描述】:

我正在尝试读取 yaml 文件,替换其中的一部分并将结果写入同一个文件,但出现属性错误。

代码

import yaml
import glob
import re
from yaml import load, dump
from yaml import CLoader as Loader, CDumper as Dumper
import io

list_paths = glob.glob("my_path/*.yaml")

for path in list_paths:    
    with open(path, 'r') as stream:
        try:
            text = load(stream, Loader=Loader)
            text = str(text)
            print text
            if "my_string" in text:
                start = "'my_string': '"
                end = "'"
                m = re.compile(r'%s.*?%s' % (start,end),re.S)
                m = m.search(text).group(0)
                text[m] = "'my_string': 'this is my string'"  
        except yaml.YAMLError as exc:
            print(exc)
    with io.open(path, 'w', encoding = 'utf8') as outfile:
        yaml.dump(text, path, default_flow_style=False, allow_unicode=True)

错误 我收到yaml_dump 行的此错误

AttributeError: 'str' object has no attribute 'write' 

到目前为止我已经尝试过什么

  • 未将文本转换为字符串,但随后在 m.search 行出现错误:

    TypeError:预期的字符串或缓冲区

  • 先转换为字符串,然后再转换为dict,但我从代码text: dict(text) 中得到此错误:ValueError: dictionary update sequence element #0 has length 1; 2 is required

Yaml 文件

my string: something
string2: something else

预期结果:yaml 文件

my string: this is my string
string2: something else

【问题讨论】:

    标签: python python-2.7 yaml


    【解决方案1】:

    要停止出现该错误,您需要做的就是更改

    with io.open(path, 'w', encoding = 'utf8') as outfile:
        yaml.dump(text, path, default_flow_style=False, allow_unicode=True)
    

    with open(path, 'w') as outfile:
        yaml.dump(text.encode("UTF-8"), outfile, default_flow_style=False, allow_unicode=True)
    

    正如另一个答案所说,此解决方案只是将字符串 path 替换为打开的文件描述符。

    【讨论】:

    • 这允许我重写 yaml 文件,但由于我是从字符串写入的,所以结果是这个 `"{my_string: this is my string, 'string2': 'something else'}"。有关如何解决此问题的任何建议?
    • 感谢您更改代码。这就是我现在得到的:'{country: this is the country field with annotations , ''something'': ''something''}'
    • 你希望输出是什么?
    • 我需要它没有花括号和引号。我找到的解决方案是将扩展名更改为.txt,修改文件并将扩展名更改回.yaml
    • 您正在做的是将您的 yaml 对象转换为字符串,然后转储该字符串。只需将其转换回 yaml 对象,以便在您将其写入文件时工作。即yamlData = load(text.encode("UTF-8"))yaml.dump(yamlData, outfile, default_flow_style=False, allow_unicode=True)
    【解决方案2】:

    这个

    yaml.dump(text, path, default_flow_style=False, allow_unicode=True)
    

    如果pathstr,则不可能。它必须是一个打开的文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-11
      • 2021-07-07
      • 1970-01-01
      • 2011-08-12
      • 2018-07-21
      • 2020-11-26
      相关资源
      最近更新 更多