我遇到了Python列表的问题。我的代码需要3个变量(项目名称,ID,位置)的文件存储,所以我使用一个有点复杂的系统来解决这个问题。每个项目名称及其ID都存储在.txt
文件中,具体取决于其位置(myLocation
的位置表示它们存储在myLocation.txt
中。)在文件内部,它们存储为一个每行都有名称ID对,例如:
item1, id1
item2, id2
我得到的错误是IndexError: list index out of range
。我已经找到了答案,但我找不到有效的解决方案。
我的代码如下:
#!/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()
这是我的输出:
[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
这似乎很奇怪。非常感谢任何提供帮助的人。
答案 0 :(得分:1)
我想在这一行:
loadedItems[itemInfoToLoad[1]] = [itemInfoToLoad[2], ''.join(loc.split())[:-4]] # explained below
你需要:
loadedItems[itemInfoToLoad[0]] = [itemInfoToLoad[1], ''.join(loc.split())[:-4]] # explained below
因为列表中只有两个元素
检查loc.split,因为代码中有[:-4],解释中有[:-3]