2

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?

3
  • output : <_csv.reader object at 0x00482E30> Commented Mar 12, 2016 at 21:05
  • What happens if you change the name of the variable you're storing the output of csv.reader()? Commented Mar 12, 2016 at 21:07
  • do you want to print the whole csv file as a list or just row by row? Commented Mar 12, 2016 at 21:14

4 Answers 4

2

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"]
Sign up to request clarification or add additional context in comments.

1 Comment

It works. I was trying to solve this one hour before i ask question here. Thanks :)
2

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

Comments

0

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]

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.