读取文本文件一行中的第一个单词时出现 IndexError

IndexError when reading the first word in a line of a text file

我正在尝试遍历文本文件中的行,并且只需要以 "From".

开头的行

如果我将行分成一个列表并检查零索引,我得到第一行(以 "From" 开头),但随后我得到一个 IndexError: list index out范围.

当我没有 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()

这应该有效-

with open('file.txt', 'r') as f:
    res = [line.strip() for line in f if line.strip().startswith('From')]

这将为您提供以 From.

开头的行列表