astra astra - 2 months ago 17
Python Question

Read all columns from CSV file?

I am trying to read in a CSV file and then take all values from each column and put into a separate list. I do not want the values by row. Since the CSV reader only allows to loop through the file once, I am using the seek() method to go back to the beginning and read the next column. Besides using a Dict mapping, is there a better way to do this?

infile = open(fpath, "r")
reader = csv.reader(infile)

NOUNS = [col[0] for col in reader]
infile.seek(0) # <-- set the iterator to beginning of the input file

VERBS = [col[1] for col in reader]
infile.seek(0)
ADJECTIVES = [col[2] for col in reader]
infile.seek(0)
SENTENCES = [col[3] for col in reader]

Answer

Something like this would do it in one pass:

kinds = NOUNS, VERBS, ADJECTIVES, SENTENCES = [], [], [], []
with open(fpath, "r") as infile:
    for cols in csv.reader(infile):
        for i, kind in enumerate(kinds):
            kind.append(cols[i])