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>You could feed the <code>reader</code> to <a href="https://docs.python.org/3.5/library/functions.html#zip" rel="nofollow"><code>zip</code></a> and unpack it to variables as you wish.</p>

<pre><code>import csv

with open('input.csv') as f:
    first, second, third, fourth = zip(*csv.reader(f))
    print('first: {}, second: {}, third: {}, fourth: {}'.format(
        first, second, third, fourth
    ))
</code></pre>

<p>With following input:</p>

<pre><code>1,2,3,4
A,B,C,D
</code></pre>

<p>It will produce output:</p>

<pre><code>first: ('1', 'A'), second: ('2', 'B'), third: ('3', 'C'), fourth: ('4', 'D')
</code></pre>

python python-3.x csv list-comprehension