Writing rows in a csv using dictionaries in a loop (python 3)
<p>IÂ´m writing on a csv file by adding each row in a loop and using dictionaries. The following is the code:</p>

<pre><code>fieldnames = ['id', 'variable1', 'variable2']
f = open('file.csv', 'w')   
my_writer = csv.DictWriter(f, fieldnames)
my_writer.writeheader()
f.close()   

for i in something:

    something where I get data for mydict      

    with open('file.csv', 'a+b') as f:
    header = next(csv.reader(f))
    dict_writer = csv.DictWriter(f, header)
    dict_writer.writerow(mydict)
</code></pre>

<p>I was sure this code worked for me some years ago but probably I was using python2. Now IÂ´m using python 3 and it shows the following error:</p>

<pre><code>header = next(csv.reader(f))

StopIteration
</code></pre>

<p>What may be the problem? Thanks</p>

<p>My solution was:</p>

<pre><code>fieldnames = ['id', 'variable1', 'variable2']

f= open('file.csv', 'w', newline='')
my_writer = csv.DictWriter(f, fieldnames)
my_writer.writeheader()

for i in something:

   something where I get data for mydict   

    writer.writerow(mydict)

f.close()
</code></pre>

python python-3.x csv for-loop dictionary