Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Writing a folder and its contents to a ZipFile

Is it possible to write a folder and its contents to an existing ZipFile? I've been messing around with this for a while and can only manage to write the folder structure to the archive, anything inside the folder isn't copied. I don't want to point to a specific file, because the idea is that the folder contents can change and the program will just copy the whole folder into the archive no matter what is inside.

Currently I have,

myzipfile.write('A Folder\\Another Folder\\') 

but I want the contents of 'Another Folder' to be copied as well not just the empty folder

Hopefully you understand what I mean.

like image 447
Artharos Avatar asked Sep 13 '11 10:09

Artharos


People also ask

How do I convert a folder to a ZipFile?

Press and hold (or right-click) the file or folder, select (or point to) Send to, and then select Compressed (zipped) folder. A new zipped folder with the same name is created in the same location. To rename it, press and hold (or right-click) the folder, select Rename, and then type the new name.

How do I create an archive in Python?

Create a zip archive from multiple files in PythonCreate a ZipFile object by passing the new file name and mode as 'w' (write mode). It will create a new zip file and open it within ZipFile object. Call write() function on ZipFile object to add the files in it. call close() on ZipFile object to Close the zip file.


1 Answers

Use os.walk:

import os
for dirpath,dirs,files in os.walk('A Folder/Another folder'):
  for f in files:
    fn = os.path.join(dirpath, f)
    myzipfile.write(fn)
like image 126
phihag Avatar answered Sep 21 '22 22:09

phihag