【问题标题】:Read data from txt file in dictionary format以字典格式从txt文件中读取数据
【发布时间】:2021-05-20 06:38:08
【问题描述】:

如何将从 txt 文件中读取的数据转换为字典格式。

txt 文件中的行数:

A1, 5, Apples
B1, 3, Oranges

期望的输出:

{'A1':[5.0,'Apples'], 'B1':[3.0,'Oranges']}

只设法编写了这些代码:

fr = open('products.txt','r')
for line in fr.readlines():
    code, name, price = line.split(',')
    print(line)
    
    fr.close()

【问题讨论】:

  • 字典键值选择的逻辑是什么?

标签: python dictionary file-handling


【解决方案1】:

你可以使用理解:

result = {line.strip().split(',')[0]: [line.strip().split(',')[1], line.strip().split(',')[2]] for line in open('products.txt','r')}

或者没有理解:

result = {}

with open('products.txt','r') as fr:
    for line in fr:
        parts = line.strip().split(',')
        result[parts[0]] = [parts[1], parts[2]]
print(result)

【讨论】:

    【解决方案2】:
    my_dict = {}
    fr = open('products.txt','r')
        for line in fr.readlines():
            code, name, price = line.split(',')
            my_dict[code] = [name,price]
            print(line)
        
        fr.close()
    

    【讨论】:

    • 虽然这可能会回答问题,但如果您还可以在答案中添加一些解释,例如代码的工作原理等,那会很好。
    【解决方案3】:

    您可以为每一行创建一个empty dictionary 和update 字典,还可以去掉 price 的值以去除逗号分割后的剩余空间:

    data = {}
    
    fr = open('products.txt','r')
    for line in fr.readlines():
        code, price, name = line.split(',')   # price is the middle item, name is last
        print(line)
        data.update({code:[float(price.strip()), name.strip()]})
        
    fr.close()   #Keep this outside the loop
    

    输出:

    {'A1': [5.0, 'Apples'], 'B1': [3.0, 'Oranges']}
    

    【讨论】:

    • 感谢指点,我刚刚复制了问题中的代码
    • 我收到一个错误,ValueError: could not convert string to float
    • 那是因为你有code, name, price = line.split(',')改成code, price, name= line.split(',')
    • 我也添加了输出,检查一次@zeerock
    【解决方案4】:

    你已经接近了,但你有一些错误和一些遗漏的东西......

    out_d = {}  # init an empty dict
    fr = open('products.txt','r')
    for line in fr.readlines():
        code, price, name = line.split(', ') # not code, name, price
        print(line)
        out_d[code] = [float(price), name]  # adds a new dict entry
    fr.close()  # gets dedented
    print(out_d)
    

    一些事情...
    (1) 根据您的输入文件,您要在', ' 上拆分,而不仅仅是','
    (2) 看起来您的输入文件的顺序是代码/价格/名称而不是代码/名称/价格
    (3) 您需要将价格从字符串转换为浮动
    (4) 你的fr.close() 缩进太远了。它需要去齿。

    此外,当您刚开始时,可​​以使用 open() 和 close()。但是有一个更好的方法,称为上下文管理器,它会自动为您执行close()。基本上,它看起来像这样:

    out_d = {}  # init an empty dict
    with open('products.txt','r') as fr:  # this creates a context
        for line in fr.readlines():
            code, price, name = line.split(', ') # not code, name, price
            print(line)
            out_d[code] = [float(price), name]
    # fr.close() -- this line now goes away
    print(out_d)
    

    上面,fr.close() 行消失了,因为with 块完成时with open 调用close。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-09
      • 1970-01-01
      • 1970-01-01
      • 2017-02-24
      • 1970-01-01
      • 2016-05-27
      • 1970-01-01
      • 2018-11-01
      相关资源
      最近更新 更多