【发布时间】:2021-09-04 17:34:11
【问题描述】:
我正在尝试遍历文本文件中的行,并且只想要以 "From" 开头的行。
如果我将该行拆分为一个列表并检查零索引,我会得到第一行(以 "From" 开头),但随后我得到一个 IndexError: list index out of range .
当我没有split 字符串并且只使用line.startswith("From") 方法时它起作用了。
file_name = input("Enter file name: ")
try:
fhandle = open(f"./src/{file_name}", "r")
except:
print("file open err")
quit()
for line in fhandle:
line = line.strip()
words = line.split()
# IndexError
if words[0] == "From": print(line)
# This works
if line.startswith("From"): print(line)
fhandle.close()
【问题讨论】:
-
您试用的文件的典型内容是什么?他们中的任何一个都有空行吗?
-
欢迎来到 SO。请拨打tour,阅读How do I ask a good question? 和How to create a Minimal, Reproducible Example。提供整个堆栈跟踪和文件样本,其中至少包括第一行。
-
@quamrana 是的,好吧,我想我明白了。谢谢!
标签: python list filehandle