首页 > 解决方案 > 为什么 readline() 没有从我的 .txt 中获取所有单词

问题描述

我正在打开一个文本文件,逐行读取并去除尾随的 '\n' 并将其附加到带有以下代码的列表中。执行此操作时,有些单词会丢失。谁能告诉我为什么?

def compare(t, w):
    c = {}
    m = []
    for line in t:
        lines = t.readline()
        word = lines.strip()
        m.append(word)
    for x in m:
        c[x] = c.get('x', 0)
    if w in c:
        print('True')
    else:
        print('False')


fin = open('words.txt')

compare(fin, 'expect')

标签: pythonfilereadline

解决方案


不要.readlinefor line in t循环内使用。每次迭代都会读取一个新行,并在 .readline 中读取下一行,因此每次迭代都会跳过一行。


推荐阅读