python - 第一行无法从 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', '.']]
另外,有没有办法将所有列表中的所有字符都小写?
解决方案
您正在丢弃 first 返回的值readline()
,这就是输出中缺少文件第一行的原因。您可以将文件对象作为迭代器进行迭代:
joined = []
for line in f:
joined.append(line.split())
print(joined)
推荐阅读
- cluster-analysis - 如何确定 R 中分类数据的聚类方法?
- javascript - 如何在 Svelte 中执行 window.scrollTo(0,0)
- android-espresso - InteractionBuilder 中没有匹配器。如何使用其类指定 Kakao 视图 UI 元素?
- python - 将使用 Brython 3.7.5 的 Python 标准发行版库导入 Angular8 项目
- c# - 根据屏幕上的另一个 Picker 设置 Picker 数据
- c# - 打开编辑和打开受密码保护的 PowerPoint 演示文稿
- knex.js - 尽管检查存在重复 PRIMARY KEY 条目
- c - for循环中哪个变量的新用户输入
- javascript - Angular Owl 日期时间选择器标签和按钮未本地化
- node.js - Node.JS & Mongo.DB - 返回集合的内容