astra astra - 1 month ago 5x
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] # <-- set the iterator to beginning of the input file

VERBS = [col[1] for col in reader]
ADJECTIVES = [col[2] for col in reader]
SENTENCES = [col[3] for col in reader]


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):