Search code examples
pythonarchivepython-zipfile

ZipFile bad directory structure


I try make some scripts which helps me zip a file from selected dir.

I have:

import sys
import os
import zipfile

source_dir = "C:\\myDir\\yourDir\\"
zip = zipfile.ZipFile("C:\\myDir\\yourDirZip.zip","w",allowZip64=True)


for root, dirs, files in os.walk(source_dir):
    for f in files:
        zip.write(os.path.join(root,f))

zip.close()

After execution, in yourDirZip.zip is:

myDir/
    yourDir/
      ...

I expect directly only yourDir or even only content of yourDir

Have you any ideas on how I can get what I want?


Solution

  • You can specify arcname parameter in the write method:

    import sys
    import os
    import zipfile
    
    source_dir = "C:\\myDir\\yourDir"
    zip = zipfile.ZipFile("C:\\myDir\\yourDirZip.zip","w",allowZip64=True)
    
    
    for root, dirs, files in os.walk(source_dir):
        for f in files:
            zip.write(os.path.join(root,f), arcname=f)
    
    zip.close()