Zastosuj kompresję GZIP do pliku CSV w Pythonie

Próbuję napisać dataframe do gziped csv w Pythonie, używając:

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')

To tworzy plik csv o nazwie ' foo-YYYYMMDD.csv.gz", a nie rzeczywiste archiwum gzip.

Próbowałem też dodać to:

#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)
Która również zawodzi. Jakieś pomysły?
Author: user2752159, 2016-05-12

4 answers

Użycie {[0] } ze słowem kluczowym argument {[1] } powinno stworzyć archiwum gzip. Przetestowałem go używając tych samych argumentów słów kluczowych co ty i zadziałało.

Być może będziesz musiał uaktualnić pandy, ponieważ gzip nie został zaimplementowany do wersji 0.17.1, ale próba użycia go na poprzednich wersjach nie spowoduje błędu, a po prostu wytworzy zwykły plik csv. Możesz określić aktualną wersję pand, patrząc na wyjście pd.__version__.

 59
Author: root,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-12 19:01:28

Robi się to bardzo łatwo z pand

import pandas as pd

Zapis ramki danych pandy na dysk jako gunzip compressed csv

df.to_csv('dfsavename.csv.gz', compression='gzip')

Odczyt z dysku

df = pd.read_csv('dfsavename.csv.gz', compression='gzip')
 32
Author: Ioannis Nasios,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-06 10:55:53

Z dokumentacji

import gzip
content = "Lots of content here"
with gzip.open('file.txt.gz', 'wb') as f:
    f.write(content)

Z pandas

import gzip


content = df.to_csv(
      sep='|',
      header=True,
      index=False,
      quoting=csv.QUOTE_ALL,
      quotechar='"',
      doublequote=True,
      line_terminator='\n')

with gzip.open('foo-%s.csv.gz' % todaysdatestring, 'wb') as f:
    f.write(content)

Sztuczka polega na tym, że to_csv wyświetla tekst, jeśli nie podasz mu nazwy pliku. Następnie wystarczy przekierować ten tekst do metody gzip write.

 9
Author: piRSquared,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-12 17:07:31
with gzip.open('foo-%s.csv.gz' % todaysdatestring, 'wb') as f:
    f.write(df.to_csv(sep='|', index=False, quoting=csv.QUOTE_ALL))
 0
Author: Alexander,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-12 17:05:43