我正在尝试编写一些代码,以读取文本文件并打印每行的第一个字母。我当前的代码是:
f=open("testfile1.txt","r")
for line in f:
words=line.split()
print(words[0])
这样,应该将字符串拆分为单个单词,但是当我运行代码时,我收到一条错误消息,指出列表索引超出范围。我尝试过人们在同一主题上遇到的类似问题的解决方案,但是当我使用相同的代码时,会出现此错误。谁能解释为什么会这样,我该如何解决? 谢谢。
答案 0 :(得分:2)
听起来像是空行,所以下面的应该起作用:
f=open("testfile1.txt","r")
for line in f:
words=line.split()
if words:
print(words[0])
f.close()
with open
:更好,
with open("testfile1.txt", "r") as f:
for line in f:
words = line.split()
if words:
print(words[0])
答案 1 :(得分:1)
错误听起来像文件中有空行。您只需要检测它们即可。此外,在python中有一个方便的技巧可以遍历文件行!可以按照以下步骤进行。
# in python the default file mode is "r", or read.
with open("testfile1.txt") as r:
for line in r:
# detect empty lines with python's default boolean values
if line:
print(line.split()[0])