编写Yaml文件:属性错误

芭芭拉

我正在尝试读取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
凯莉·鲁兹(Kellie Lutze)

要停止收到该错误,您需要做的就是更改

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打开的文件描述符替换字符串

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章