Ich habe Probleme mit einer Python-Liste. Mein Code erfordert die Speicherung von 3 Variablen (Name, ID, Ort) und so benutze ich ein etwas komplexes System, um dies zu erreichen. Jeder Objektname und seine ID werden je nach Standort in einer .txt
Datei gespeichert. (Ein Speicherort von myLocation
bedeutet, dass sie in myLocation.txt
gespeichert sind.) Sie werden in der Datei mit einem Namen-ID-Paar für jede Zeile gespeichert. Beispiel:IndexError: Listenindex außerhalb des Bereichs (Python 3)
item1, id1
item2, id2
Der Fehler, den ich bekomme, ist IndexError: list index out of range
. Ich habe nach Antworten gesucht, aber ich kann keine Lösung finden, die funktioniert.
Mein Code ist unten:
#!/usr/bin/env python3
from time import sleep
# Set variables to be used later
loadedItems = {} # Stores loaded items (as values) and item info (as list keys)
def newItem(name, id, location):
print("[INFO] Adding new item.")
try:
print("[INFO] Checking if " + str(location) + ".txt exists.")
itemfile = open((str(location) + ".txt"), "a") # Ready to append to file if exists
print(location + ".txt exists.")
except:
print("[INFO] " + str(location) + ".txt does not exist.")
print("[INFO] Trying to create " + str(location) + ".txt.")
try:
itemfile = open((str(location) + ".txt"), "a+") # Creates file if it does not already exist
print("[INFO] Created " + str(location) + ".txt.")
except:
print("[WARN] Could not create " + str(location) + ".txt to store items. Your item was not saved.")
print(" Try manually creating the file with 'touch " + str(location) + ".txt'.")
return # Exits function
print("[INFO] Trying to write to " + str(location) + ".txt.")
try:
itemfile.append(str(name) + ", " + str(id) + "\n") # Write to it
print("[INFO] Wrote to " + location + ".txt.")
except:
print("[WARN] Could not write to " + str(location) + ".txt. Your item was not saved.")
return
print("[INFO] Wrote to " + str(location) + ".txt.")
itemfile.close() # Close file
print("[INFO] Closed " + str(location) + ".txt.")
def loadItems():
print("[INFO] Loading items.")
print("[INFO] Trying to open location file.")
try:
locfile = open("locations.txt", "r") # Open list of all locations
print("[INFO] Opened location file.")
except:
print("[INFO] Location file does not exist, creating it.")
locfile = open("locations.txt", "w+")
locfile.close()
print("[INFO] Created and closed location file. Nothing to read.")
return # exit loadItems()
print("[INFO] Reading location file.")
locations = locfile.read().split("\n") # List of locations
print("[INFO] Read location file. Found " + str(len(locations)) + " locations.")
locfile.close() # Close location file
emptyLocs = 0
emptyItems = 0
for loc in locations:
if loc != '': # NOT a blank location
itemfile = open(loc) # Open location specified in location file
localItems = itemfile.read().split("\n") # Get list of items and their ids
print("[DEBUG] localItems: " + str(localItems)) # For debugging purposes, to be removed
del localItems[-1] # Removes last item from localItems (it is a blank line!)
print("[DEBUG] localItems: " + str(localItems)) # For debugging purposes, to be removed
for localItem in localItems: # localItem is misleading, it's actually a list with item name AND id.
itemInfoToLoad = localItem.split(", ") # Make list with 1st = name and 2nd = id
loadedItems[itemInfoToLoad[1]] = [itemInfoToLoad[2], ''.join(loc.split())[:-4]] # explained below
"""
Explanation of above: create a new key in loadedItems with the name of
itemInfoToLoad[1], which is the item name. Set its value to a list that
is [id, location]. The ''.join(loc.split())[:-3] is to remove the .txt
extension (and any trailing whitespace) so we go from myAwesomeLocation.txt
to myAwesomeLocation. Bazinga.
"""
elif loc == '': # Blank location
sleep(0.1)
emptyLocs = (emptyLocs + 1)
print("[INFO] Loaded variables. Found " + str(emptyLocs) + " empty location entries and " + str(emptyItems) + " empty items.")
loadItems()
Hier ist meine Ausgabe:
[INFO] Loading items.
[INFO] Trying to open location file.
[INFO] Opened location file.
[INFO] Reading location file.
[INFO] Read location file. Found 2 locations.
[DEBUG] localItems: ['item1, id1', 'item2, id2', '']
[DEBUG] localItems: ['item1, id1', 'item2, id2']
Traceback (most recent call last):
File "main.py", line 76, in <module>
loadItems()
File "main.py", line 63, in loadItems
loadedItems[itemInfoToLoad[1]] = [itemInfoToLoad[2], ''.join(loc.split())[:-4]] # explained below
IndexError: list index out of range
Diese ziemlich seltsam scheint. Vielen Dank im Voraus an alle, die Hilfe anbieten.
'[: -3]' ist ein Tippfehler - '.txt' ist 4 Zeichen lang. Sonst danke dafür, ich habe Python counts von 0 vergessen. –