5

I have a csv file that has one column of records that looks like this:

test1
test2
test3
...

I imported them into a Python list using this:

import csv

results = []
with open('test.csv', newline='') as inputfile:
    for row in csv.reader(inputfile):
        results.append(row)

print(results)

That worked fine, however, it prints them out like this:

[['test1'],['test2'],['test3']]

How would I adjust my code to have them print out in a single list instead like this:

['test1','test2','test3']

and, is one output more preferred than the other? I realize it is use-case dependent. I am just curious how others work with imported lists via .csv, and what advantage one would have over the other.

Thanks!

2
  • 4
    You don't have csv... you just have... text... Commented Sep 16, 2017 at 4:42
  • that's true. maybe in this specific example a .txt file would have been more appropriate. Commented Sep 16, 2017 at 4:46

1 Answer 1

19

Try the following code

import csv

results = []
with open('test.csv', newline='') as inputfile:
    for row in csv.reader(inputfile):
        results.append(row[0])

print(results)
Sign up to request clarification or add additional context in comments.

1 Comment

this works well. And if your csv has multiple columns, but you only want to use one of the columns as a list, just change the index number in (row[0]).

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.