manty
manty

Reputation: 297

How to create zip of a specific folder using shutil

I'm trying to zip all the folders of a particular directory separately with their respective folder names as the zip file name just the way how winzip does.My code below:

folder_list = os.walk('.').next()[1] # bingo
print folder_list

for each_folder in folder_list:
    shutil.make_archive(each_folder, 'zip', os.getcwd())

But what it is doing is creating a zip of one folder and dumping all other files and folders of that directory into the zip file.LIke that it is doing for all the folders inside the current directory.
Any help on this !!!

Upvotes: 1

Views: 3595

Answers (2)

Beri
Beri

Reputation: 11600

I don;t think that is possible. You could look at the source.

In particular, at line 683 you can see that it explicitly passes compression=zipfile.ZIP_DEFLATED if your Python has the zipfile module, while the fallback code at line 635 doesn't pass any arguments besides -r and -q to the zip command-line tool.

You could try this one:

args = ['tar', '-zcf', dest_file_name, '-C', me_directory, '.']
res = subprocess.call(args)

If you want to get list of directories use some well written libs:

for (root, directories, _) in os.walk(my_dir):
  for dir_name in directories:
     path_to_dir = os.path.join(root, dir_name)// don't make concat, like a+'//'+b, thats not enviroment saint

Upvotes: 0

manty
manty

Reputation: 297

With a little more research in shutil, I'm now able to make my code work. Below is my code:

import os, shutil

#Get the list of all folders present within the particular directory
folder_list = os.walk('.').next()[1]

#Start zipping the folders
for each_folder in folder_list:
    shutil.make_archive(each_folder, 'zip', os.getcwd() + "\\" + each_folder)

Upvotes: 2

Related Questions