title: How to compress csv file into zip archive directly?
body: <p>I am generating a number of csv files dynamically, using the following code:</p>
  
  <pre><code>import csv
  fieldnames = ['foo1', 'foo2', 'foo3', 'foo4']
  with open(csvfilepath, 'wb') as csvfile:
      csvwrite = csv.DictWriter(csvfile, delimiter=',', fieldnames=fieldnames)
      csvwrite.writeheader()
      for row in data:
          csvwrite.writerow(row)
  </code></pre>
  
  <p>To save space, I want to compress them.<br>
  Using the <code>gzip</code> module is quite easy:</p>
  
  <pre><code>with gzip.open("foo.gz", "w") as csvfile :
      csvwrite = csv.DictWriter(csvfile, delimiter=',', fieldnames=fieldnames)
      csvwrite.writeheader()
      for row in data:
          csvwrite.writerow(row)
  </code></pre>
  
  <p>But I want the file in 'zip' format.</p>
  
  <p>I tried the <code>zipfile</code> module, but I am unable to directly write files into the zip archive.</p>
  
  <p>Instead, I have to write the csv file to disk, compress them in a zip file using following code, and then delete the csv file.</p>
  
  <pre><code>with ZipFile(zipfilepath, 'w') as zipfile:
      zipfile.write(csvfilepath, csvfilename, ZIP_DEFLATED)
  </code></pre>
  
  <p>How can I write a csv file directly to a compressed zip similar to gzip?</p>