Search code examples
pythonpandascsvdownloadzip

saving individual df into a zip file


I have 2 pandas data frames as in this example:

                   A         B         C         D
2000-01-01  0.298399 -0.738440 -0.505438  0.324951
2000-01-02  1.300686 -0.938543 -1.850977  0.868467

and

                   A         B         C         D
2000-01-03  0.328032  0.325845 -0.289175  0.393732
2000-01-04  0.091853 -1.450642 -0.544152  1.073248 

I would like to save them as individual csv files inside a single zip file. The end result would be:

myzipfile.zip

containing df1.csv and df2.csv; which I then download the zip file to the local drive.

There are many examples on how to concat 2+ DF into one large DF and download as a zip file. But I have not been able to find a case where multiple DF are added as individual csv files to a single zipfile.

Thank you


Solution

  • Archiving files is not pandas specific. You can use standard python lib shutil:

    import os, shutil
    
    ...
    
    tmp_path = "an/empty/tmp/dir"
    
    df1.to_csv(os.path.join(tmp_path, "df1.csv"))
    df2.to_csv(os.path.join(tmp_path, "df2.csv"))
    
    shutil.make_archive('dfs.zip', 'zip', root_dir=tmp_path, base_dir=tmp_path)