读取文件并将内容存储到字典中 - Python

时间:2016-02-19 22:16:13

标签: python file dictionary

我正在尝试将文件的内容存储到字典中,并且当我调用其键时我想返回一个值。文件的每一行都有两个用逗号分隔的项(首字母缩写词和相应的短语),共有585行。我想将逗号左侧的首字母缩略词存储到键中,将逗号右侧的短语存储到值中。这就是我所拥有的:

def read_file(filename):

    infile = open(filename, 'r')

    for line in infile:
        line = line.strip() #remove newline character at end of each line
        phrase = line.split(',')
        newDict = {'phrase[0]':'phrase[1]'}

    infile.close()

这是我在尝试查找值时得到的结果:

>>> read_file('acronyms.csv')
>>> acronyms=read_file('acronyms.csv')
>>> acronyms['ABT']
Traceback (most recent call last):
  File "<pyshell#65>", line 1, in <module>
    acronyms['ABT']
TypeError: 'NoneType' object is not subscriptable
>>> 

如果我将return newDict添加到函数正文的末尾,那么当我调用{'phrase[0]':'phrase[1]'}时,它显然会返回read_file('acronyms.csv')。我也试过{phrase[0]:phrase[1]}(没有单引号),但返回相同的错误。谢谢你的帮助。

3 个答案:

答案 0 :(得分:1)

 0:00:00->000000
 1:05:23->010523
 2:10:46->021046
 3:16:09->031609
 4:21:32->042132
 5:26:55->052655
 6:32:18->063218
 7:37:41->073741
 8:43:04->084304
 9:48:27->094827
10:53:50->105350
11:59:13->115913
13:04:36->130436
14:09:59->140959
15:15:22->151522
16:20:45->162045
17:26:08->172608
18:31:31->183131
19:36:54->193654
20:42:17->204217
21:47:40->214740
22:53:03->225303
23:58:26->235826

答案 1 :(得分:0)

def read_file(filename):
    infile = open(filename, 'r')
    newDict = {}
    for line in infile:
        line = line.strip() #remove newline character at end of each line
        phrase = line.split(',', 1) # split max of one time
        newDict.update( {phrase[0]:phrase[1]})
    infile.close()
    return newDict

你的原文在循环的每次迭代中创建一个新的字典。

答案 2 :(得分:0)

首先,您将在循环的每次迭代中创建一个新字典。相反,创建一个字典并在每次越过一行时添加元素。其次,'phrase[0]'包含撇号,使其成为一个字符串,而不是对刚刚创建的短语变量的引用。

另外,请尝试使用with关键字,以便以后不必显式关闭该文件。

def read(filename):
    newDict = {}
    with open(filename, 'r') as infile:
        for line in infile:
            line = line.strip() #remove newline character at end of each line
            phrase = line.split(',')
            newDict[phrase[0]] = phrase[1]}

    return newDict
相关问题