【问题标题】:Python - Write into txt file for my list of dictionariesPython - 为我的字典列表写入 txt 文件
【发布时间】: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


【解决方案1】:

下面('Information'下的数据是一个列表,你需要遍历列表条目)

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')

【讨论】:

  • 这很好用!文件末尾只有一个小问题,有 3 个空换行符。有办法解决吗?
  • @xeith 代码已修改 - 再试一次。告诉我。
  • 哦,太好了,它解决了问题!抱歉,您能否在代码中添加 cmets 以便我更好地理解最后一部分?关于 len(data) - 1 那部分。还有,我怎样才能给你提供代表点数?我是堆栈溢出的新手
  • @xeith - 如果有,请尝试提出具体问题。
  • 这是我试图了解它是如何工作的部分。如果 idx != len(data) - 1: 。谢谢!
【解决方案2】:
with open("shoes_db.txt", 'w') as f:
    for entry in data:
        f.write(entry['Name'] + '\n')
        f.write(entry['Date & Time'] + '\n')

【讨论】:

    猜你喜欢
    • 2021-10-12
    • 2021-08-30
    • 1970-01-01
    • 2022-08-22
    • 2018-11-07
    • 2014-05-02
    • 2018-01-05
    • 1970-01-01
    • 2013-06-08
    相关资源
    最近更新 更多