简体   繁体   中英

Python: printing from txt file to list

I would like to convert this text file to a list. But I'm having some error. Please enlighten me on why I have an error.

goods= {}
    with open("goods.txt") as f:
        for key, val in f:
            key[0] = inv[1], int(inv[2])
    print(goods) 

goods.txt : a1 marker 5 a2 pen 5 a3 eraser 4 a4 pencil 10

Prints out List :

goods = {'A':['marker', 5], 'B':['pens',5] … }
  • I don't think that this is the result you are getting. The actual result is an error. You can not just interpret an opened text-file as dictionary.

  • goods = {} is never used.

  • you try to assign a value to key[0], which is a local loop-variable key[0] = inv[1], int(inv[2])

Eg have a look at this code, maybe it helps you understand this a little better...

with open("goods.txt", mode='r') as f:
    for line in f:
        print(line.split(' '))

You can do something like this

goods= {}
with open("goods.txt") as f:
    for line in f:
        itemId,itemName,qty = line.split()
        goods[itemId] = [itemName,int(qty)]
print(goods)

This will output:

{'a1': ['marker', 5], 'a2': ['pen', 5], 'a3': ['eraser', 4], 'a4': ['pencil', 10]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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