【发布时间】:2018-01-17 09:51:14
【问题描述】:
我正在尝试读取 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
【问题讨论】:
标签: python python-2.7 yaml