0

I have a directory composed of 3 folders :
----- 001
----- 002
----- 003

I'd like to create 3 archives named 001.zip, 002.zip and 003.zip. Each archive has to be composed of the content of the folder.

I use the zipfile library and I managed to make an archive of one folder :

import os, zipfile    
zf = zipfile.ZipFile('C:/zipfile4.zip', mode='w')
for dirpath,dirs,files in os.walk("C:/Test/002"):
    for f in files:
        fn = os.path.join(dirpath, f)
        zf.write(fn)

But I don't know how to make to create many archives in a row, using that zipfile library.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Julien
  • 699
  • 3
  • 14
  • 30
  • I tried the snippet I wrote in my post. This one works well but only for a folder. Actually I'd like to adapt the snippet to make one archive to one folder by a loop. – Julien Apr 28 '15 at 12:18
  • Then just try to make a loop with it and see how it goes. – ljk321 Apr 28 '15 at 12:21

1 Answers1

1

Using your code sample as a basis, this should work:

import os
import zipfile

dir = "C:/Test/002"

# get list of all subdirectories in the directory
subdirs = [subdir for subdir in os.listdir(dir) if os.path.isdir(os.path.join(dir, subdir))]

# create a zip archive for each subdirectory
for subdir in subdirs:
    zf_name = "C:/" + subdir + ".zip"
    zf = zipfile.ZipFile(zf_name, mode='w')
    for dirpath,dirs,files in os.walk(os.path.join(dir, subdir)):
        for f in files:
            fn = os.path.join(dirpath, f)
            zf.write(fn)
geckon
  • 8,316
  • 4
  • 35
  • 59
  • Thaks for your help. I tried your code and each archive has been well created. But the thing is that the content of the folders has been lost. Do you know how to resolve it ? – Julien Apr 28 '15 at 12:26
  • @Julien I'm sorry but what do you mean by lost? It seems to work fine for me. – geckon Apr 28 '15 at 12:35
  • I mean I had many files (around 5 Mo) in the folders 002, 003 and so on. And by using the script the archives 002.zip and 003.zip are empty. – Julien Apr 28 '15 at 12:37
  • @Julien Are you sure about this? Are you using exactly the same script I posted? I use it with the `dir` and `zf_name` changed (I'm on Linux) and it works fine. Please double check that you have the files in the subdirectories before running the script. – geckon Apr 28 '15 at 12:39
  • Yes I checked the folders. All the files are present in C:/Test/002, C:/Test/003 and so on. I only changed `dir` as C:/Test. After running the script I have two archives created : C:/002.zip and C:/003.zip. But they are empty. – Julien Apr 28 '15 at 13:04
  • @Julien, Ah, I know now. I have edited my answer, try the edited script please. – geckon Apr 28 '15 at 13:23
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/76456/discussion-between-geckon-and-julien). – geckon Apr 28 '15 at 13:26