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)
Share:
11,601

Related videos on Youtube

JD2775
Author by

JD2775

Updated on September 15, 2022

Comments

  • JD2775
    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
      Jeff Mercado over 6 years
      You don't have csv... you just have... text...
  • Theo F
    Theo F about 3 years
    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]).