lik123
lik123

Reputation: 13

Zip directories from listed ones

I am relatively new to Python, I am trying to make a script which will only zip subfolders that I define in a list, with their content of course. I tried modifying various codes from Stack Overflow and whatever I found on internet but either I zip all subfolders, or I zip subfolders that I want but without content.

List could be full path to subfolder or can I define the path to the root folder and then specify subfolders?

This is the idea: 3 subfolders 1,2,3 and I want to zip only subfolders 1 and 3. I added the last code that I was modifying but I just can't return the list in a function.

Folder
|- SubFolder1
|  |- file1.txt
|  |- file2.txt
|- SubFolder2
|  |- file1.txt
|  |- file2.txt
|- SubFolder3
|  |- file1.txt
|  |- file2.txt

The code:

import os
import zipfile


list=["SubFolder1", "SubFolder3"]

def zipdir(path, ziph):

# ziph is zipfile handle
  for root, dirs, files in os.walk(path):
    for file in files:
        ziph.write(os.path.join(root, file))


if __name__ == '__main__':

zipf = zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED)
zipdir(**list**, zipf)
zipf.close()

Upvotes: 1

Views: 66

Answers (1)

ffrosch
ffrosch

Reputation: 1383

I modified your code and think this way it should work as expected if I understand your request correctly. Please check out this thread too, I think it's pretty much what you are looking for ;-)

1) os.walk goes through each of your subfolders, too. So just wait until each subfolder becomes the "root" (here is an example).

2) Check whether the folder is contained in the list. If it is, zip all files within this folder

3) Recreate the subfolder structure relative to your original root-folder

import os
import zipfile

rootpath = r'C:\path\to\your\rootfolder'
list=["SubFolder1", "SubFolder3"]

def zipdir(path, ziph, dirlist):
  # ziph is zipfile handle
  for root, dirs, files in os.walk(path):
    if os.path.basename(root) in dirlist:
      for file in files:
        file_path = os.path.join(root, file)
        relative_path = os.path.relpath(file_path, path)
        ziph.write(file_path, relative_path)


if __name__ == '__main__':
  zipf = zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED)
  zipdir(rootpath, zipf, list)
  zipf.close()

Upvotes: 2

Related Questions