0
我遇到了Python列表的問題。我的代碼需要3個變量(項目名稱,ID,位置)的文件存儲,所以我用一個有點複雜的系統來處理這個問題。每個項目名稱及其ID都存儲在.txt
文件中,具體取決於它們的位置(myLocation
的位置表示它們存儲在myLocation.txt
中。)在文件內部,它們每行存儲一個名稱ID對,例如:IndexError:列表索引超出範圍(Python 3)
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
這似乎很奇怪。非常感謝任何提供幫助的人。
'[:-3]'是一個錯字 - '.txt'長度爲4個字符。否則,謝謝你,我忘了Python的計數從0開始。 –