我正在尝试读取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
要停止收到该错误,您需要做的就是更改
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] 删除。
我来说两句