【发布时间】:2020-08-27 18:43:12
【问题描述】:
假设我有这样存储的字典数据集列表:
data = [
{'Name': 'Sneaker shoes', 'Date & Time': '2019-12-03 18:21:26', 'Information': ['Sizes from 38 to 44', 'Comes in 5 different colour', 'Rated 4.3 out of 5 stars']},
{'Name': 'Worker boots', 'Date & Time': '2018-11-05 10:12:15', 'Information': ['Sizes from 38 to 44', 'Comes in 2 different colour', 'Rated 3.7 out of 5 stars']},
{'Name': 'Slippers', 'Date & Time': '2018-10-05 13:15:44', 'Information': ['Sizes from 38 to 42', 'Comes in 3 different colour', 'Rated 4.1 out of 5 stars']}
]
我一直在尝试将数据写入 txt 文件,但我不知道如何将其编码出来。这就是我所做的
shoes_database = open("shoes_db.txt", 'w')
for value in data:
shoes_database.write('\n'.join([value.get('Name'), str(value.get('Date & Time')), str(value.get('Information')), '\n']))
shoes_database.close()
“名称”和“日期和时间”中的值已正确存储到文件中。但是,对于“信息”,我无法将每个鞋子信息存储到一个新行中,并且没有方括号和“”,因为它是一个列表。
这是我想写并存储在我的 shoes_db.txt 文件中的内容
Sneaker shoes
2019-12-03 18:21:26
Sizes from 38 to 44
Comes in 5 different colour
Rated 4.3 out of 5 stars
Worker boots
2018-11-05 10:12:15
Sizes from 38 to 44
Comes in 2 different colour
Rated 3.7 out of 5 stars
Slippers
2018-10-05 13:15:44
Sizes from 38 to 42
Comes in 3 different colour
Rated 4.1 out of 5 stars
希望对我的 python 代码有一些答案。我仍在从中学习,因为它是我项目的一部分。我也仅限于使用python标准库,所以不能使用任何第三方库。
【问题讨论】:
-
您可能需要在已有的循环中编写另一个循环。
-
哦,我明白了,我错过了!谢谢!
标签: python list file dictionary