首页 > 解决方案 > 第一行无法从 Python 中的文本文件加载

问题描述

我是 Python 新手,我不明白为什么我的代码无法加载第一行。有人可以看看吗?

我的代码是:

f = open("test.txt")
line = f.readline()

joined=[]

while line:
    line=f.readline().split()
    for x in line:
        joined.append(line)

f.close()

print(joined)

“test.txt”文件如下所示:

This is the 1st line !
This is the 2nd line .
This is the 3rd line ?
This is the 4th line
This is the 5th line .

我明白了(第一行丢失,条目也重复):

[['This', 'is', 'the', '2nd', 'line', '.'], ['This', 'is', 'the', '2nd', 'line', '.'], ['This', 'is', 'the', '2nd', 'line', '.'], ['This', 'is', 'the', '2nd', 'line', '.'], ['This', 'is', 'the', '2nd', 'line', '.'], ['This', 'is', 'the', '2nd', 'line', '.'], ['This', 'is', 'the', '3rd', 'line', '?'], ['This', 'is', 'the', '3rd', 'line', '?'], ['This', 'is', 'the', '3rd', 'line', '?'], ['This', 'is', 'the', '3rd', 'line', '?'], ['This', 'is', 'the', '3rd', 'line', '?'], ['This', 'is', 'the', '3rd', 'line', '?'], ['This', 'is', 'the', '4th', 'line'], ['This', 'is', 'the', '4th', 'line'], ['This', 'is', 'the', '4th', 'line'], ['This', 'is', 'the', '4th', 'line'], ['This', 'is', 'the', '4th', 'line'], ['This', 'is', 'the', '5th', 'line', '.'], ['This', 'is', 'the', '5th', 'line', '.'], ['This', 'is', 'the', '5th', 'line', '.'], ['This', 'is', 'the', '5th', 'line', '.'], ['This', 'is', 'the', '5th', 'line', '.'], ['This', 'is', 'the', '5th', 'line', '.']]

但所需的输出是:

[['This', 'is', 'the', '1st', 'line', '!'], ['This', 'is', 'the', '2nd', 'line', '.'],  ['This', 'is', 'the', '3rd', 'line', '?'], ['This', 'is', 'the', '4th', 'line'], ['This', 'is', 'the', '5th', 'line', '.']]

另外,有没有办法将所有列表中的所有字符都小写?

标签: pythonpython-3.x

解决方案


您正在丢弃 first 返回的值readline(),这就是输出中缺少文件第一行的原因。您可以将文件对象作为迭代器进行迭代:

joined = []
for line in f:
    joined.append(line.split())
print(joined)

推荐阅读