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>One thing nobody noticed so far is that you're trying to store names and last names in two separate lists. This is not going to be very convenient to use later on. Therefore despite other answers show correct possible solutions to read names and last names from csv into two separate lists, I'm going to propose you to use a single list of dicts instead:</p>

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

list_of_names = []
for row_f1 in csv_f1:
    list_of_names.append({
       "vorname": row_f1[2],
       "name": row_f1[3]
    })
</code></pre>

<p>Then you can iterate over this list and take the value you want. For example to simply print the values:</p>

<pre><code>for row in list_of_names:
    print(row["vorname"])
    print(row["name"])
</code></pre>

<p>And the last but not least, you could build this list also by using list comprehension (kinda more Pythonic):</p>

<pre><code>list_of_names = [
   {
       "vorname": row_f1[2],
       "name": row_f1[3]
   }
   for row_f1 in csv_f1
]
</code></pre>

<p>As I said, I appreciate other answers. They solve the issue of csv reader being iterable and not a list-like object.<br>
Nevertheless I see a little bit of XY Problem in your question. I've seen so many times attempts to store entity properties (name and last name are obviously related properties and form a simple entity together) in multiple lists. It always ends up with the code which is hard to read and maintain.</p>

python loops csv for-loop restart