maciej.o
maciej.o

Reputation: 187

How to pack several DataFrames into one file using zipfile

I have a few DataFrames that I need to zip to one file. This is my code:

df_list = [ojcowskieDF,mateczneDF]
with zipfile.ZipFile('final.zip', 'w') as zipF:
    for file in df_list:
        zipF.write(file, compress_type=zipfile.ZIP_DEFLATED)

But I get this error:TypeError: stat: path should be string, bytes, os.PathLike or integer, not DataFrame Does anyone know how to zip a few DF? Thanks for your help

Upvotes: 2

Views: 369

Answers (1)

Timeless
Timeless

Reputation: 37902

You need first to convert your dataframes to .csv by using pandas.DataFrame.to_csv or to .xlsx by using pandas.DataFrame.to_excel.

import zipfile
import os

list_df = [ojcowskieDF, mateczneDF]

with zipfile.ZipFile('final.zip', 'w') as zf:
    i=1 #this iterator to make sure each .csv will have a different name
    for df in list_df:
        df.to_csv(f'sample_{i}.csv') #this will convert the dataframe to a .csv
        zf.write(f'sample_{i}.csv') #this will put the .csv in the zipfile
        os.remove(f'sample_{i}.csv') #this will delete the .csv created 
        i+=1

Upvotes: 2

Related Questions