Skip to main content
 首页 » 编程设计

python之写入 yaml 文件 : attribute error

2024年09月07日16sxdcgaq8080

我正在尝试读取一个 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:字典更新序列元素 #0 的长度为 1; 2 是必需的

Yaml 文件

my string: something 
string2: something else 

预期结果:yaml 文件

my string: this is my string 
string2: something else 

请您参考如下方法:

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

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