python阅读文件无限循环

时间:2015-03-27 00:14:57

标签: python readfile

pronunciation_file = open('dictionary.txt')
pronunciation = {}
line = pronunciation_file.readline()
while line != '':
    n_line = line.strip().split(' ' , 1)
    pronunciation[n_line[0]] = n_line[1].strip()
    line = pronunciation_file.readline()
print(pronunciation)

代码是将单词及其发音的文件转换成字典(键是单词,值是发音),例如' A AH0 \ n ...'进入{' A':' AH0' ...} 问题是,如果我把打印放在循环中,它打印正常(但它打印所有未完成的字典)但是如果我把打印放在循环外面像上面那样,shell返回任何东西,当我关闭它时,它会提示程序仍在运行(可能是一个无限循环)

请帮助

我也试过删掉前几百个单词并运行程序,它适用于非常短的文件,但它开始在一定长度内没有返回任何内容:|

2 个答案:

答案 0 :(得分:6)

这不是如何从文件中读取:

# with will also close your file
with open(your_file) as f:
    # iterate over file object
    for line in f:
         # unpack key/value for your dict and use rstrip
         k, v = line.rstrip().split(' ' , 1)
         pronunciation[k] = v

您只需打开文件并遍历文件对象即可。如果要从字符串末尾删除,请使用.rstrip(),也不需要在同一行上调用strip两次。

您还可以将代码简化为仅使用dictgenerator expression

with open("dictionary.txt") as f:
    pronunciation = dict(line.rstrip().split(" ",1) for line in f)

答案 1 :(得分:2)

未经测试,但如果你想使用while循环,那么这个成语更像是这样:

pronunciation={}
with open(fn) as f:
    while True:
        line=f.readline()
        if not line:
            break
        l, r=line.split(' ', 1)    
        pronunciation[l]=r.strip()

但是,用于逐行读取文件的更现代的Python习语是使用for循环,就像Padraic Cunningham的答案一样。 while循环更常用于在Python中通过固定块读取二进制文件固定块。

相关问题