编写yaml文件:属性错误

时间:2018-01-17 09:51:14

标签: python python-2.7 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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

yaml.dump(text, path, default_flow_style=False, allow_unicode=True)
如果pathstr,则无法

。它必须是一个打开的文件。