简体   繁体   中英

Printing .csv file as list in python

My Code:

import csv

with open('serialnumber.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')
    your_list = list(reader)

print(your_list)

.csv file:

hello,bye

Printed output :

[['hello', 'bye']]

I need to get list like this :

['hello', 'bye']

What I'm doing wrong?

The reason you are getting [["hello", "bye"]] is because, if the CSV has multiple lines, they will be items inside the first list.

You can get what you want by accessing the first item of your_list like this:

>>> print(your_list[0])
["hello", "bye"]

There is no problem with your code. It is just that you are making a list out of all rows of the csv. That is why you are getting a list of lists. To get each row as a list you can simply iterate over the reader and you will get a list for each row. This technique is particularly useful when you have a large file.

import csv

with open('serialnumber.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')
    for r in reader:
      print r

You can see a two-dimensional array of CSV file [print(r) for r in your_list]

    import csv

with open('serialnumber.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')
    your_list = list(reader)

#print(your_list)
[print(r) for r in your_list]

If you want to flatten the whole csv reader i would use list comprehenstion

import csv

with open('serialnumber.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')
    _list = [word for _iter in reader for word in _iter]
print(_list)

You could also use sum :

_list = sum(reader, [])

Example one row csv :

hello,bye

Output:

['hello', 'bye']

Example multi-row csv :

hello,bye,bye
bye,bye,hello
bye,hello,bye

Output:

['hello', 'bye', 'bye', 'bye', 'bye', 'hello', 'bye', 'hello', 'bye']

If your csv file has just one row you could use plain print :

import csv

with open('serialnumber.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')
    print(*reader)

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