Tisal
Tisal

Reputation: 155

Zipping files to specified path in python

I have been learning python since few weeks. In one of the problem I have to zip the files contained in list to the specified path. I am using python in Windows.

python zipall.py C:\temp C:\example

should extract particular type of files from C:\example, which I did successfully in some list (say listX). Now the job is to make zip file C:\temp consisting of the all files in listX in zipped form. How to perform this operation in Python?

I have to make zip file in specified path (here C:\temp) containing all files that are contained in list (here listX).

I tried zipfile.ZipFile() as below:

zip_name = zipfile.ZipFile(tozip, 'w')
l=len(listX)
ctr=0
for thelist in listX:
    zip_name = zipfile.ZipFile(tozip+str(ctr), 'w')
    if ctr<=l:
        ctr+=1
    zip_name.write(thelist,'zip')

It certainly creates 'l' zip files but I have to create 'l' zip files within path given by tozip ('C:\temp' above)

Upvotes: 3

Views: 215

Answers (1)

Owen S.
Owen S.

Reputation: 7855

zipfile.ZipFile creates the output ZIP archive for you in the location you want the ZIP file written to. But you need to give it a filename, not a directory name. From your description it sounds like tozip was set to C:\temp. In which case you should use os.path.join to construct a filename, like this:

import os.path
tozip = os.path.join(r'C:\temp', 'out.zip')

That should get you an archive created in the directory you want. Note that you may do this instead, using the handy 'tempfile' library to avoid hardcoding a Windows path into your script:

import os.path
from tempfile import gettempdir
tozip = os.path.join(gettempdir(), 'out.zip')

Now, as you're iterating through the list, I think you want to add each file one at a time to the single archive you're creating, right? Your code is looping through listX, but for each file in listX it's creating a new ZIP archive, and adding that file to the new archive. Also, as it goes through the list, because each time you're assigning the new ZIP archive to zip_name, you've completely forgotten about the archive that you really want to have your output in. So I think you want this instead:

theZip = zipfile.ZipFile(tozip, 'w')
for elem in listX:
    theZip.write(elem)

Upvotes: 1

Related Questions