Dan Me
Dan Me

Reputation: 2163

How can I create a zip?

How can I add files and zip the folder?

So far, using zipfile, I’m able to create a zip.

Upvotes: 0

Views: 474

Answers (1)

Taku
Taku

Reputation: 33724

How can I create a folder to add files and zip the folder?

You can do what you want by following these steps:

To create a folder, use os.mkdir like this:

import os
os.mkdir('spam') # your folder name

then you can write files to it or use shutil.copy to make copies of existent files.

# to write files:
with open('./spam/eggs.txt', 'w') as fp: # creates a text file in spam named eggs.txt
    fp.write('hello') # write hello

# to copy files
import shutil
shutil.copy('eggs.txt', './spam/eggs.txt') # copy eggs.txt from the current working dir to spam folder

then to zip the folder, you had the right idea, to use zipfile like this:

from zipfile import ZipFile, ZIP_DEFLATED

zipfp = ZipFile('spam.zip', 'w', ZIP_DEFLATED) # create a new zip file named spam.zip

for root, dirname, files in os.walk('./spam'): # walk in the spam folder
    [zipfp.write(os.path.join('./spam',file)) for file in files] # write them to the zip file
zipfp.close()

A complete example:

import os
from zipfile import ZipFile, ZIP_DEFLATED
os.mkdir('spam')
with open('./spam/eggs.txt', 'w') as fp: 
    fp.write('hello')
with ZipFile('spam.zip', 'w', ZIP_DEFLATED) as zipfp:
    for root, dirname, files in os.walk('./spam'): 
        [zipfp.write(os.path.join('./spam',file)) for file in files] 

The result of this code is it produces a compressed folder named spam.zip and in the zip file, there's a txt file named eggs.txt which contains the text 'hello'.

To clarify for the OP:

[zipfp.write(os.path.join('./spam',file)) for file in files]

is equivalent to:

for file in files:
     zipfp.write(os.path.join('./spam',file))

it's just simpler to write it using list comprehension.

Upvotes: 1

Related Questions