[英]Python - Write into txt file for my list of dictionaries
假設我有這樣存儲的字典數據集列表:
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標准庫,所以我不能使用任何第三方庫。
下面(“信息”下的數據是一個列表,您需要遍歷列表條目)
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']}
]
with open("shoes_db.txt", 'w') as f:
for idx, entry in enumerate(data):
f.write(entry['Name'] + '\n')
f.write(entry['Date & Time'] + '\n')
for info in entry['Information']:
f.write(info + '\n')
if idx != len(data) - 1:
f.write('\n')
with open("shoes_db.txt", 'w') as f:
for entry in data:
f.write(entry['Name'] + '\n')
f.write(entry['Date & Time'] + '\n')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.