2016-11-19 91 views
0

文件名:dictionary.txt从文本文件导入到一个字典

YAHOO:YHOO 
GOOGLE INC:GOOG 
Harley-Davidson:HOG 
Yamana Gold:AUY 
Sotheby’s:BID 
inBev:BUD 

代码:

infile = open('dictionary.txt', 'r') 
content= infile.readlines() 
infile.close() 

counters ={} 
for line in content: 
     counters.append(content) 
     print(counters) 

我试图导入file.txt的内容到词典中。我已经通过堆栈溢出进行搜索,但请以简单的方式回答(而不是打开...)

+1

与文件打交道时,你应该使用'open()的函数'这样或那样的(无论如何) – RomanPerekhrest

回答

0

首先,不是明确打开和关闭文件,而是使用with语句打开文件,关闭文件自动在块的结尾处。其次,由于文件对象是类似于迭代器的对象(可迭代一次),因此可以遍历行并使用:字符分割它们。您可以dict函数中做所有这些事情作为generator expression

with open('dictionary.txt') as infile: 
    my_dict = dict(line.strip().split(':') for line in infile) 
+0

它的作品!谢谢 – Alireza

0

我认为你没有分号在你的钥匙。 在这种情况下,你应该:

#read lines from your file 
lines = open('dictionary.txt').read().split('\n') 
#create an empty dictionary 
dict = {} 
#split every lines at ':' and use the left element as a key for the right value 
for l in lines: 
    content = l.split(':') 
    dict[content[0]] = content[1]