Python: How to restart a FOR loop, which iterates over a csv
<p>I am using Python 3.5 and I wanna load data from a csv into several lists, but it only works exactly one time with a FOR-Loop. Then it loads 0 into it.</p>

<p>Here is the code:</p>

<pre><code>f1 = open("csvfile.csv", encoding="latin-1")
csv_f1 = csv.reader(f1, delimiter=';')

list_f1_vorname = []
for row_f1 in csv_f1:
    list_f1_vorname.append(row_f1[2])

list_f1_name = []
for row_f1 in csv_f1:   # &lt;-- HERE IS THE ERROR, IT DOESNT WORK A SECOND TIME!
    list_f1_name.append(row_f1[3])    
</code></pre>

<p>Does anybody know how to restart this thing?
Many thanks and best regards,
Saitam</p>

<p>The simple answer is to iterate over the csv once and store it into a list.
something like</p>

<pre><code>my_list = []
for row in csv_f1:
    my_list.append(row)
</code></pre>

<p>or what abukaj wrote with</p>

<pre><code>csv_f1 = list(csv.reader(f1, delimiter=';'))
</code></pre>

<p>and then move on and iterate over that list as many times as you want.</p>

<p>However if you are only trying to get certain columns then you can simply do that in the same for loop.</p>

<pre><code>list_f1_vorname = []
list_f1_name = []
for row in csv_f1:
    list_f1_vorname.append(row[2])
    list_f1_name.append(row[3])
</code></pre>

<p>The reason it doesn't work multiple times is because it is an iterator...so it will iterate over the values once but not restart at beginning again after it has already iterated over the data.</p>

python loops csv for-loop restart