【问题标题】:IndexError when reading the first word in a line of a text file读取文本文件行中的第一个单词时出现 IndexError
【发布时间】: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()

【问题讨论】:

标签: python list filehandle


【解决方案1】:

这应该可行-

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

这将为您提供以 From 开头的行列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 2014-08-03
    • 2012-11-27
    • 1970-01-01
    相关资源
    最近更新 更多