Error: Mixing iteration and read methods would lose data问题的解决

错误:在Python 2.7中,统计words.txt文件中不含e的单词的个数和总的单词数。

运行如下代码会报错‘ Mixing iteration and read methods would lose data' (或者输出结果与预期不符)

def has_no_e(word):
    return not 'e' in word
    
fin = open('words.txt')
no_e_num = 0
for line in fin:
    word = line.strip()
    if has_no_e(word):
        print word
        no_e_num = no_e_num + 1

print 'no_e_num is',no_e_num

allnum = len(fin.readlines())
print 'allnum is ',allnum

原因:可能是对fin文件进行for循环之后,又企图执行fin.readlines()操作,导致多重迭代问题。(似乎与指针的位置有关)

解决方法:在for循环之后,fin.readlines()操作之前,添加

fin.seek(0)

这条语句的作用是重新移动文件读取指针到开头的位置。

参考

  • StackOverflow中相似问题的解答:

猜你喜欢

转载自blog.csdn.net/cunane/article/details/80790483
今日推荐