【发布时间】:2022-11-10 21:08:51
【问题描述】:
我坚持将列表的字典写入 .txt 文件。
我有一个这样的 lict 字典:
product_menu_list = {"Shirt": ["Red", "Orange", "Purple"], "Dress": ["Blue", "Yellow", "Green"]}
要将其写入 .txt 文件,我写道:
product_lines = product_menu_list
with open('product_record.txt', 'w') as f:
for line in product_lines:
f.write(json.dumps(product_lines))
f.write('\n')
通过编写上面的代码,我可以得到:
{"Shirt": ["Red", "Orange", "Purple"], "Dress": ["Blue", "Yellow", "Green"]}
那不是我想要的格式。
但是,我想要的是在 .txt 文件中逐行编写,例如:
Shirt:
Red
Orange
Purple
Dress:
Blue
Yellow
Green
我怎样才能达到预期的输出?
【问题讨论】:
-
如果您不想输出 JSON 格式,请不要使用
json.dumps。
标签: python list dictionary