简体   繁体   中英

"IndexError: list index out of range" when opening and printing a txt file

I'm taking a programming fundamentals class at uni. For an assignment, I have to open a txt file in Python and print the elements from it in a sort of table. The txt file is a list of customer names along with their IDs and some other info. The file is laid out like this:

C1, James, 0, 100

C2, Lily, 0, 30

With a total of 7 lines of customer info.

This is the code I currently have:

file = open('customers.txt', "r")
    content = file.readline()
    while content:
        content = content.split(',')
        sys.stdout.write('{:<4}{:>12}{:>18}{:>9}'.format(content[0],content[1],content[2],content[3],"\n"))
        content = file.readline()
    file.close

Which prints the customer info as required, but after printing all the customers it gives this error:

    sys.stdout.write('{:<4}{:>12}{:>18}{:>9}'.format(content[0],content[1],content[2],content[3],"\n"))
IndexError: list index out of range

I'm unsure of how to stop this error. Do I need to tell Python that there is 7 lines of info to print? What if I was importing a file and didn't know how many lines of info there would be?

I also have to add this info to a list in Python, which I currently fail at doing, but that's a serparate issue.

Any help would be greatly appreciated:)

Just adding this to show you can simplify a bit of logic if desired. For example, use print and f-strings instead of format strings.

file_contents = """\
C1, James, 0, 100
C2, Lily, 0, 30
"""

for line in file_contents.strip().split('\n'):
    content = line.split(',')
    print(f'{content[0]:<4}{content[1]:>12}{content[2]:>18}{content[3]:>9}')

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