简体   繁体   中英

How to append list index Python

Please help, I can't find it.

Why can I append row but not row[2] ? It crashes. I'm using Python 3.4.3.

import csv

with open("file.csv", encoding="UTF8") as csvfile:
    read = csv.reader(csvfile, delimiter=";")

    original = []

    for row in read:
        original.append(row[2])


csvfile.close()
print(original)

Thanks

This looks to be a frustrating debugging experience.

One possibility is that there's a last line in the file that has only one item which is causing the issue.

A quick way to look at the situation (depending how long your file is) might be to throw in a print and see what's going on, line by line:

for row in read:
    try:
        original.append(row[2])
    except:
        print(row)

If you run with this, you may be able to see what happens just before the crash .

You may want to be a little more descriptive on what the crash is. It's famously difficult to help with such a vague description. A little more effort will help people to help you more effectively.

I would suggest you do not try and print the whole of your CSV list at the end, this can cause some IDEs to lock up for a long time.

Instead you could just print the last few entries to prove it has worked:

print("Rows read:", len(original)
print(original[-10:])

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