'list index out of range python txt
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
Solution 1:[1]
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.
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | AlphabetSoup |
| Solution 2 | Pozay |
