简体   繁体   中英

How can I solve this error: “builtins.IndexError: list index out of range”?

I am trying to create a small function to clean data and organize into table format. The data is just txt with name, address and phone number each seperated by onto another line and then repeated.

However, I am continuously getting the following error:

Traceback (most recent call last):
  Python Shell, prompt 2, line 19
builtins.IndexError: list index out of range

Here is my code.

f = open("numbers.txt", "r")


table = []
column = 0

for i in range(3):
    table.append([])
    for line in range(column, total_lines, 3):
        table[column].append(file_into_list[line])
        column = column + 1

for i in range(len(table[0])):
    print(table[0][i] + "\t" + table[1][i] + "\t" + table[2][i])

Again, the original data is just in the following format:

John
123-123-1231
5 Bald st
jane
123-123-1234
6 balls st
...

I think this what you may be looking for:

f = open("numbers.txt", "r")

table = []

for i in range(3):
    row = []
    for line in range(3):
        row.append(f.readline().strip())
    table.append(row)

for row in table:
    print(row[0] + "\t" + row[1] + "\t" + row[2])

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