簡體   English   中英

Python:從 txt 文件打印到列表

[英]Python: printing from txt file to list

我想將此文本文件轉換為列表。 但我有一些錯誤。 請告訴我為什么我有錯誤。

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

goods.txt : a1 記號筆 5 a2 鋼筆 5 a3 橡皮擦 4 a4 鉛筆 10

打印出列表

goods = {'A':['marker', 5], 'B':['pens',5] … }
  • 我不認為這是你得到的結果。 實際結果是錯誤的。 您不能只將打開的文本文件解釋為字典。

  • goods = {}從未使用過。

  • 您嘗試為 key[0] 分配一個值,這是一個本地循環變量key[0] = inv[1], int(inv[2])

例如看看這段代碼,也許它可以幫助你更好地理解這一點......

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

你可以做這樣的事情

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

這將 output:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM