简体   繁体   中英

Index out of range Python query

I am trying to read data from a text file into a python list and then the user is supposed to choose which entry to edit which will then be overwritten back into the text file. When I read it out into the list, the list only winds up containing one item.

def editEntry():
f = open("address_book.txt", "r")

for line in f:
    Name, Age, Address, City = line.split(',')

    editList = []
    editList.append([Name, Age, Address, City])
    print (editList , "\n")

choice = int(input("Which entry would you like to edit?" + "\n"))
test = editList[choice]
print (test)

When that code is run, I can only select the index 0 when I want to select 0, 1 or 2.

Any help guys?

You empty editList every time before adding to it. Put editList = [] before the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM