can't zip files from Jupyter Notebook

Viewed 3597

I try to zip files, I used the example from https://thispointer.com/python-how-to-create-a-zip-archive-from-multiple-files-or-directory/

with ZipFile('sample2.zip', 'w') as zipObj2:

   # Add multiple files to the zip
   zipObj2.write('sample_file.csv')

sample2.zip is created, but it is empty. Of course that the csv file exists and is not empty.

  • I run this code from Jupyter Notebook

edit: I'm using relative paths -

input_dir = "../data/example/" 
with zipfile.ZipFile(os.path.join(input_dir, 'f.zip'), 'a') as zipObj2: 
zipObj2.write(os.path.join(input_dir, 'f.tif'))
2 Answers

you tried to close zip file to save ?

from zipfile import ZipFile

with ZipFile('sample2.zip', 'w') as zipObj2:
   zipObj2.write('sample_file.csv')
   zipObj2.close()

I'm a little confused by your question, but if I'm correct it sounds like you're trying to place multiple CSV files within a single zipped file? If so, this is what you're looking for:

#initiate files variable that contains the directory from which you wish to zip csv files
files=[f for f in os.listdir("./your_directory") if f.endswith('.csv')]

#initalize empty DataFrame 
all_data = pd.DataFrame()

#iterate through the files variable and concatenate them to all_data 
for file in files:
df = pd.read_csv('./your_directory' + file)
all_data = pd.concat([all_data, df])

Then call your new DataFrame(all_data) to verify that contents were transferred.

Related