简体   繁体   中英

Python - Having trouble with IndexError: list index out of range

Thanks in advance for your answers. Ive tried to research my own answer to this problem for hours with no avail. I'm now asking for advice not the answer perhaps as it is an assignment question for university.

I have a program that stores a set of data in single line records. This is saved in a file named 'sales.txt'

There is a variable (customerIDInput) brought over from another function which is basically the customer ID.

My program is supposed to search the records line by line, finding every record that has the 'customerIDInput' in index 0.

I am getting an error on what I would assume is the last repeat of the loop. Index out of range. I have initially thought this was the last (\\n) and therefore not having any index at all... However I have put in a rstrip(\\n') and the problem has not been solved.

I realize that I am new to python and the answer is probably very simple however I'm in over my head I think and it seems its time to ask you wise people here :)

Attached is the function I am having difficulty with.

def searchFile ():

sales = open('sales.txt', 'r')    
transaction = 'START'

while transaction != ' ':

    transaction = sales.readline()
    transactionStrip = transaction.rstrip('\n')        
    transaction_list = transactionStrip.split()

    if transaction_list[0] == str(customerIDInput):    
        customerEntry = transaction_list 
        print('matching records are: ',customerEntry)

sales.close()

The readline method on file objects will return an empty string when you reach the end of the file. When you split the empty string, you'll get an empty list, which has no first element. This is why transaction_list[0] gives you an IndexError at the end of the file.

There are a few different ways you could fix this issue. Keeping close to your current code, you could adjust your while loop's condition to look for transaction being an empty string (rather than a string with a single space) and read one line ahead:

transaction = sales.readline()    # read first line
while transaction != "":
    # do stuff with non-empty transaction line

    transaction = sales.readline()  # read next line

However, a more natural way to iterate over the lines in a file is to simply use a for loop directly on the file object:

for transaction in sales:
    # do stuff

Iterating this way will stop automatically at the end of the file.

在实际尝试获取transaction_list[0]以避免IndexError之前,您可以通过调用if transaction_list: (检查其中是否有任何项目)来简单地检查此类索引是否存在。

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