【问题标题】:writing a dict (of list) to a file.txt将 dict (of list) 写入 file.txt
【发布时间】: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


【解决方案1】:

尝试:

product_lines = product_menu_list
with open('product_record.txt', 'w') as f:
    for line in product_lines:
        f.write(json.dumps(line))
        f.write('
')

【讨论】:

  • 这和他们已经在使用的一样??
猜你喜欢
  • 2021-02-28
  • 2016-08-12
  • 2012-11-29
  • 1970-01-01
  • 1970-01-01
  • 2022-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多