Importing .csv values as single list in Python
11,601
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)
Related videos on Youtube
Author by
JD2775
Updated on September 15, 2022Comments
-
JD2775 over 1 year
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!
-
Jeff Mercado over 6 yearsYou don't have csv... you just have... text...
-
-
Theo F about 3 yearsthis 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])
.