我有一个字典,我用它来填充每个键的YAML配置文件。
{'id': ['HP:000111'], 'id1': ['HP:000111'], 'id2': ['HP:0001111', 'HP:0001123'])}
使用ruamel.yaml
import ruamel.yaml
import sys
yaml = ruamel.yaml.YAML()
with open('yaml.yml') as fp:
data = yaml.load(fp)
for k in start.keys():
data['analysis']['hpoIds'] = start.get(key)
with open(f"path/yaml-{k}.yml","w+") as f:
yaml.dump(data, sys.stdout)
这是我得到的输出
analysis:
# hg19 or hg38 - ensure that the application has been configured to run the specified assembly otherwise it will halt.
genomeAssembly: hg38
vcf:
ped:
proband:
hpoIds: "['HP:000111','HP:000112','HP:000113']"
但这就是我需要的
hpoIds: ['HP:000111','HP:000112','HP:000113']
我试过使用字符串工具,如strip, replace,但没有
ast.literal_eval.
输出
hpoIds:
- HP:000111
- HP:000112
- HP:000113
repr
输出
hpoIds: ""['HP:000111','HP: 000112','HP:000113']""
任何帮助都将不胜感激
我不完全清楚你想做什么,为什么你打开文件'w+'表示转储
然而,如果你有一些东西出现块样式和未引号,这可以很容易地补救通过使用一个小函数:
import sys
from pathlib import Path
import ruamel.yaml
SQ = ruamel.yaml.scalarstring.SingleQuotedScalarString
def flow_seq_single_quoted(lst):
res = ruamel.yaml.CommentedSeq([SQ(x) if isinstance(x, str) else x for x in lst])
res.fa.set_flow_style()
return res
in_file = Path('yaml.yaml')
in_file.write_text("""
hpoIds:
- HP:000111
- HP:000112
- HP:000113
""")
yaml = ruamel.yaml.YAML()
data = yaml.load(in_file)
data['hpoIds'] = flow_seq_single_quoted(data['hpoIds'])
yaml.dump(data, sys.stdout)
给了:
hpoIds: ['HP:000111', 'HP:000112', 'HP:000113']
至少从2006年9月开始,YAML文件的推荐扩展名是.yaml
。