我试图写一些代码来读取文本文件,并打印每一行的第一个字母。我目前的代码是:
f=open("testfile1.txt","r")
for line in f:
words=line.split()
print(words[0])这样,字符串应该被分割成单独的单词,但是当我运行代码时,我会收到一条错误消息,表示列表索引超出了范围。我曾经尝试过类似问题的解决方案,但当我使用相同的代码时,我会得到这个错误。有人能解释一下为什么会发生这种事吗?我怎么能解决呢?谢谢。
发布于 2019-07-10 01:41:28
听起来好像有空行,所以下面的内容应该能用:
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])发布于 2019-07-10 01:41:47
这些错误听起来像是文件中有空行。您只需要检测them.Also,在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])https://stackoverflow.com/questions/56962347
复制相似问题