如何读取和存储从文本文件到字典的值。 [蟒蛇] [英] How to read and store values from a text file into a dictionary. [python]
问题描述
我试图找出如何打开一个文件,然后将其内容存储到一个字典中,使用零件号。作为关键和其他信息作为价值。所以我希望它看起来像这样:
I'm trying to figure out how to open up a file and then store it's contents into a dictionary using the Part no. as the key and the other information as the value. So I want it to look something like this:
{Part no.: "Description,Price", 453: "Sperving_Bearing,9900", 1342: "Panametric_Fan,23400",9480: "Converter_Exchange,93859"}
能够将文件中的文本存储到列表中,但是我不知道如何为一个键分配多个值。我试图这样做,而不导入任何模块。我一直在使用基本的str方法,列表方法和dict方法。
I was able to store the text from the file into a list, but I'm not sure how to assign more than one value to a key. I'm trying to do this without importing any modules. I've been using the basic str methods, list methods and dict methods.
推荐答案
对于 txt
For a txt
file like so
453 Sperving_Bearing 9900
1342 Panametric_Fan 23400
9480 Converter_Exchange 93859
你可以做
>>> newDict = {}
>>> with open('testFile.txt', 'r') as f:
for line in f:
splitLine = line.split()
newDict[int(splitLine[0])] = ",".join(splitLine[1:])
>>> newDict
{9480: 'Converter_Exchange,93859', 453: 'Sperving_Bearing,9900', 1342: 'Panametric_Fan,23400'}
您可以通过检查 line.startswith()来删除
。 ----...
'-----')
You can get rid of the ----...
line by just checking if line.startswith('-----')
.
编辑 - 如果您确定前两行包含同样的东西,那么你可以做
EDIT - If you are sure that the first two lines contain the same stuff, then you can just do
>>> testDict = {"Part no.": "Description,Price"}
>>> with open('testFile.txt', 'r') as f:
_ = next(f)
_ = next(f)
for line in f:
splitLine = line.split()
testDict[int(splitLine[0])] = ",".join(splitLine[1:])
>>> testDict
{9480: 'Converter_Exchange,93859', 'Part no.': 'Description,Price', 453: 'Sperving_Bearing,9900', 1342: 'Panametric_Fan,23400'}
将第一行添加到代码中的 testDict
中,并跳过前两个行,然后继续正常。
This adds the first line to the testDict
in the code and skips the first two lines and then continues on as normal.
这篇关于如何读取和存储从文本文件到字典的值。 [蟒蛇]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!