pythonlistfilehandle

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


I am trying to iterate over the lines in a text file, and want only the lines that start with "From".

If I split the line into a list and check the zero index, I get the first line (that starts with "From"), but then I get a IndexError: list index out of range.

When I didn't split the string and just used a line.startswith("From") method it worked.

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()

Solution

  • This should work-

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

    This will give you a list of the lines that starts with From.