我试图读取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
答案 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)
如果path
是str
,则无法。它必须是一个打开的文件。