Read all columns from CSV file?
<p>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?</p>

<pre><code>infile = open(fpath, "r")
reader = csv.reader(infile)    

NOUNS = [col[0] for col in reader]
infile.seek(0)  # &lt;-- 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]
</code></pre>

<p>This works assuming you know exactly how many columns are in the csv (and there isn't a header row).</p>

<pre><code>NOUNS = []
VERBS = []
ADJECTIVES = []
SENTENCES = []
with open(fpath, "r") as infile:
    reader = csv.reader(infile)    

    for row in reader:
        NOUNS.append(row[0])
        VERBS.append(row[1])
        ADJECTIVES.append(row[2])
        SENTENCES.append(row[3])
</code></pre>

<p>If you don't know the column headers, you're going to have to be clever and read off the first row, make lists for every column you encounter, and loop through every new row and insert in the appropriate list. You'll probably need to do a list of lists.</p>

<p>If you don't mind adding a dependency, use <a href="http://pandas.pydata.org" rel="nofollow">Pandas</a>. Use a <code>DataFrame</code> and the method <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html#pandas.read_csv" rel="nofollow"><code>read_csv()</code></a>. Access each column using the column name i.e.</p>

<pre><code>df = pandas.DataFrame.read_csv(fpath)
print df['NOUN']
print df['VERBS']
</code></pre>

python python-3.x csv list-comprehension