Python/Pandas create zip file from csv

In the to_csv() method of pandas, besides the compression type (gz, zip etc) you can specify the archive file name - just pass the dict with necessary params as the compression parameter:

compression_opts = dict(method='zip',
                        archive_name='out.csv')  
df.to_csv('out.zip', compression=compression_opts)

In the example above, the first argument of the to_csv method defines the name of the [ZIP] archive file, the method key of the dict defines [ZIP] compression type and the archive_name key of the dict defines the name of the [CSV] file inside the archive file.

Result:

├─ out.zip
│  └─ out.csv

See details in to_csv() pandas docs


Use

df.to_csv('my_file.gz', compression='gzip')

From the docs:

compression : string, optional a string representing the compression to use in the output file, allowed values are ‘gzip’, ‘bz2’, ‘xz’, only used when the first argument is a filename

See discussion of support of zip files here.


In response to Stefan's answer, add '.csv.gz' for the zip csv file to work

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

Hope that helps