Devashish Rattan
Devashish Rattan

Reputation: 11

on Creating zip file all folders from root directory are added

I am trying to zip all the files and folders present in a folder3 using python.

I have used zipFile for this. The zip contains all the folders from the root directory to the directory I want to create zip folder of.

def CreateZip(dir_name):
    os.chdir(dir_name)
    zf = zipfile.ZipFile("temp.zip", "w")
    for dirname, subdirs, files in os.walk(dir_name):
        zf.write(dirname)
        for filename in files:
            file=os.path.join(dirname, filename)
            zf.write(file)
    zf.printdir()
    zf.close()

Expected output:

toBeZippedcontent1\toBeZippedFile1.txt
toBeZippedcontent1\toBeZippedFile2.txt
toBeZippedcontent1\toBeZippedFile1.txt
toBeZippedcontent2\toBeZippedFile2.txt

Current output (folder structure inside zip file):

folder1\folder2\folder3\toBeZippedcontent1\toBeZippedFile1.txt
folder1\folder2\folder3\toBeZippedcontent1\toBeZippedFile2.txt
folder1\folder2\folder3\toBeZippedcontent2\toBeZippedFile1.txt
folder1\folder2\folder3\toBeZippedcontent2\toBeZippedFile2.txt

Upvotes: 1

Views: 794

Answers (1)

furas
furas

Reputation: 142794

walk() gives absolute path for dirname so join() create absolut path for your files.

You may have to remove folder1\folder2\folder3 from path to create relative path.

file = os.path.relpath(file)

zf.write(file)

You could try to slice it

file = file[len("folder1\folder2\folder3\\"):]

zf.write(file)

but relpath() should be better.


You can also use second argument to change path/name inside zip file

  z.write(file, 'path/filename.ext')

It can be useful if you run code from different folder and you don't use os.chdir() so you can't create relative path.

Upvotes: 0

Related Questions