title: writing to csv, only the last line ends up in the file python
body: <p>When writing to a csv file, only the last row is written.</p>
  
  <p>Here's the code </p>
  
  <pre><code>   item_keys = []
     item_values = []
     item_values2 = []#to build the list of lists
      # added newline='' because in Python3 this is required to keep an extra row being added
      with open(filename+'.csv','w',newline='') as outfile:
          writer = csv.writer(outfile)
          for key, value in jcr_rows.items():
              if write_header:
              item_keys.append(key)
              item_values.append(value)
          if write_header:
              writer.writerow(item_keys)
              write_header = False
          print(item_values)
          writer.writerow(item_values)
  </code></pre>
  
  <p>The "print(item_values)" shows two lists:</p>
  
  <pre><code>['', '1.92469', '3.394', '8.1', '98.24', '220.54971', '1.053',
  '1932-6203', '3.7', '22,077', '2611', '2.806', 'PLoS One', '2.615',
  '77.344', '0.429', 'PLOS ONE', '508,248']
  ['', '0.00155', 'Not Available', '8.4', '83.54', '0.17802', 
  'Not Available', '1024-2708','7.5', '79', '7567', '1.111', 'HONG KONG 
  MEDICAL JOURNAL', '1.062','40.584', '0.405', 'HONG KONG MED J', '1,228']
  </code></pre>
  
  <p>But only the second one gets written. If I change the write mode to "a", the headers are duplicated for each row. </p>
  
  <p>I have tried using writerows instead of writerow, but that splits the content up by at the character, and still only for one row.  </p>
  
  <p>I have tried adding</p>
  
  <pre><code>for x in item_values:
      writer.writerow(x)
  </code></pre>
  
  <p>this separated the characters for one row, also.</p>
  
  <p>I have tried building the lists into a list of lists to use with writerows but that hasn't gone well either.</p>
  
  <p>I have been round and round with this, and now I am spinning my wheels. </p>
  
  <p>Any help would be appreciated.</p>
  
  <p>UPDATE: 
  The expected output is a row of headers, which are printed with rows of related data underneath</p>
  
  <pre><code>JCR Abbreviated Title   Citable Items   ISSN       etc 
  PLOS ONE                22,077          1932-6203 
  HONG KONG MED J         79              1024-2708
  </code></pre>