Python——我的列表怎么会超出范围?
任务是让用户选择读取数据文件或写入数据文件。我知道如何写入它,但我无法理解当前的错误:我的列表超出范围 有人能告诉我我的名单是怎么超出范围的吗 我相信我做的每件事都是对的,但我真的不确定我的清单怎么会超出范围。请帮帮我,伙计们。谢谢Python——我的列表怎么会超出范围?,python,list,arraylist,range,outofrangeexception,Python,List,Arraylist,Range,Outofrangeexception,任务是让用户选择读取数据文件或写入数据文件。我知道如何写入它,但我无法理解当前的错误:我的列表超出范围 有人能告诉我我的名单是怎么超出范围的吗 我相信我做的每件事都是对的,但我真的不确定我的清单怎么会超出范围。请帮帮我,伙计们。谢谢 #Run again useAgain=bool(True) while useAgain: #Display Options print("\nYou may either read or write to the file:\n"\
#Run again
useAgain=bool(True)
while useAgain:
#Display Options
print("\nYou may either read or write to the file:\n"\
"\n'1' - To read and display records in the data file."\
"\n'2' - To order.\n")
choice=str(input("Please enter your choice here: "))
def func_read():
cs7Assn7=open("cs7Assn7.txt",'r')
line=cs7Assn7.readline()
places=line.split('+')
userID=places[0]
widgetsNum=places[1]
gidgetsNum=places[2]
doodadsNum=places[3]
print("Customer ID: ",userID,"\nNumber of Widgets: ",widgetsNum,\
"\nNumber of Gidgets: ",gidgetsNum,"\nNumber of Doodads: ",\
doodadsNum,"\n")
def func_order():
userID=str(input("Please enter your user ID(2 letters"\
" followed by 3 numbers: "))
widgetsNum=abs(int(input("Number of Widgets you would"\
" like to order: ")))
gidgetsNum=abs(int(input("Number of Gidgets you would"\
" like to order: ")))
doodadsNum=abs(int(input("Number of Doodads you would"\
" like to order: ")))
items=open("cs7Assn7.txt",'a')
items.write(str(userID) + str(abs(widgetsNum)) + str(abs(gidgetsNum))\
+ str(abs(doodadsNum)) + '\n')
items.close()
if choice=="1":
func_read()
elif choice=="2":
func_order()
useAgain=str(input("\nWould you like to run this code again? Type 'Y' to"\
" run or 'N' to stop: "))
useAgain=useAgain.lower()
if useAgain !="y":
useAgain=bool(False)
我猜,您在以下任一行中都会遇到错误:
widgetsNum=places[1]
gidgetsNum=places[2]
doodadsNum=places[3]
原因是文本文件中的某些行没有三个“+”符号。
因此,在拆分时,您没有包含4项的列表。这就是错误。错误在哪一行?我们需要更多的细节。什么线路?你试过什么?有什么例子吗?你能粘贴错误的回溯吗?我假设你在读取文件时得到了错误。您能在文件
cs7Assn7.txt
中提供错误所在的行/行吗?在func\u read
中,您假设您的4个字段由+
分隔,但在func\u顺序中,您没有在字段之间写入+
。这4个字段完全没有用任何字符分隔。两个字符串之间的+
只是将它们连接起来,而不会在字符串之间添加+
字符