繁体   English   中英

以字典格式从txt文件中读取数据

[英]Read data from txt file in dictionary format

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

txt 文件中的行:

A1, 5, Apples
B1, 3, Oranges

所需的 output:

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

您可以使用理解:

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

您可以创建一个empty dictionaryupdate每一行的字典,还可以去掉 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

OUTPUT

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

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

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()也很好。 但是有一个更好的方法来 go,称为上下文管理器,它会自动为您执行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 open调用在with块完成时close

快乐编码!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM