[英]How can I print [] without string in Python in YAML file
在我的山葯文件中,我正在嘗試
with open(fname, "w") as f:
yaml.safe_dump({'items':['test', 'test2']}, f,
default_flow_style=False, width=50, indent=4)
它以以下格式打印
items:
- 'test'
- 'test2'
我希望輸出格式如下
items: ['test', 'test2']
我怎樣才能做到這一點 ?
編輯:
這是我完整的代碼
d = {}
for m in ['B1', 'B2', 'B3']:
d2 = {}
for f in ['A1', 'A2', 'A3']:
# here i don't want any flow style
d2[f] = ['test', 'test2']
d[m] = d2
with open(fname, "w") as f:
yaml.safe_dump(d, f, default_flow_style=True, width=50, indent=8)
然后,不要把default_flow_style=False
放到與您想要的完全相反的位置 :
>>> import yaml
>>> yaml.safe_dump({'items': ['test', 'test2']}, default_flow_style=False)
'items:\n- test\n- test2\n'
>>> yaml.safe_dump({'items': ['test', 'test2']})
'items: [test, test2]\n'
對於部分文檔格式設置,可以使用自定義表示形式 ,例如:
class Items(list):
pass
def items_representer(dumper, data):
return dumper.represent_sequence('tag:yaml.org,2002:seq', data, flow_style=True)
yaml.representer.SafeRepresenter.add_representer(Items, items_representer)
result = yaml.safe_dump({
'items': Items(['test', 'test2']),
'other list': ['1', '2'],
}, default_flow_style=False)
# items: [test, test2]
# other list:
# - '1'
# - '2'
print(result)
如果要進行精細控制,並且只具有帶有流樣式的特定列表 ,則應使用ruamel.yaml (這是我的PyYAML的增強版):
import ruamel.yaml
from ruamel.yaml.comments import CommentedSeq
d = {}
for m in ['B1', 'B2', 'B3']:
d2 = {}
for f in ['A1', 'A2', 'A3']:
# here i don't want any flow style
d2[f] = CommentedSeq(['test', 'test2'])
if f != 'A2':
d2[f].fa.set_flow_style()
d[m] = d2
x = ruamel.yaml.dump(
d, Dumper=ruamel.yaml.RoundTripDumper,
default_flow_style=False, width=50, indent=8)
print(x)
會給你:
B1:
A1: [test, test2]
A3: [test, test2]
A2:
- test
- test2
B2:
A1: [test, test2]
A3: [test, test2]
A2:
- test
- test2
B3:
A1: [test, test2]
A3: [test, test2]
A2:
- test
- test2
CommentedSeq
行為就像普通的Python列表一樣,但是允許您指定注釋,設置流/塊樣式等。
ruamel.yaml
通常用於保留注釋,元素上的流/塊樣式等。 即,如果您要追加:
d2 = ruamel.yaml.load(x, Loader=ruamel.yaml.RoundTripLoader)
y = ruamel.yaml.dump(
d2, Dumper=ruamel.yaml.RoundTripDumper, width=50, indent=8)
assert x == y
斷言成立。
但是它當然也可以用於從頭生成YAML。 例如,您也可以使用CommentedMap類型並保持字典/映射的鍵有序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.