Anwenden der GZIP-Komprimierung auf eine CSV in Python Pandas

Ich versuche, einen Datenframe in eine gzippte CSV in Python-Pandas zu schreiben, indem ich Folgendes verwende:

import pandas as pd
import datetime
import csv
import gzip

# Get data (with previous connection and script variables)
df = pd.read_sql_query(script, conn)

# Create today's date, to append to file
todaysdatestring = str(datetime.datetime.today().strftime('%Y%m%d'))
print todaysdatestring

# Create csv with gzip compression
df.to_csv('foo-%s.csv.gz' % todaysdatestring,
      sep='|',
      header=True,
      index=False,
      quoting=csv.QUOTE_ALL,
      compression='gzip',
      quotechar='"',
      doublequote=True,
      line_terminator='\n')

Dies erstellt nur eine CSV mit dem Namen 'foo-YYYYMMDD.csv.gz', kein tatsächliches gzip-Archiv.

Ich habe auch versucht, dies hinzuzufügen:

#Turn to_csv statement into a variable
d = df.to_csv('foo-%s.csv.gz' % todaysdatestring,
      sep='|',
      header=True,
      index=False,
      quoting=csv.QUOTE_ALL,
      compression='gzip',
      quotechar='"',
      doublequote=True,
      line_terminator='\n')

# Write above variable to gzip
 with gzip.open('foo-%s.csv.gz' % todaysdatestring, 'wb') as output:
   output.write(d)

Welche auch fehlschlägt. Irgendwelche Ideen

Antworten auf die Frage(8)

Ihre Antwort auf die Frage