Home > Back-end >  list index out of range python txt
list index out of range python txt

Time:04-05

I have txt file which looks like:

New York,cinema,3,02/04/2022

But I've got error in list, even if this code works to another txt files without date, what's the problem?


def finished_objects():

   file = open("finished_objects.txt", "r",encoding="UTF8")
   lines = file.readlines()
   L = []  # assign empty list with name 'L'
   for line in lines:
       L.append(line.replace("\n", "").split(","))
   file.close()
   for i in range(len(L)):
       print(L[i][0], ":", L[i][1], ". Quantity:", L[i][2], ". Date: ", L[i][3])    
   return L

CodePudding user response:

You can also use "with" for opening files like,

with open("finished_objects.txt", "r",encoding="UTF8") as file:
  lines = file.readlines()
   L = []  # assign empty list with name 'L'
   for line in lines:
       L.append(line.replace("\n", "").split(","))
   # rest of your code

That way you don't have to manage the connection.

CodePudding user response:

Works fine on my end. Might be that your file has one entry with less commas than others. You could do a simple if len(L) != 4 inside your last loop to make sure you won't get errors while running.

  • Related