How to create a zip archive of a directory in Python?

后端 未结 25 2616
暗喜
暗喜 2020-11-22 07:12

How can I create a zip archive of a directory structure in Python?

25条回答
  •  伪装坚强ぢ
    2020-11-22 08:04

    For anyone else delving into this question and trying to archive the very same directory their program is in and is getting both very deep tree structures and ending up with recursion due to the zip file zipping itself, try this.

    It's a combination of Mark's answer and some extra checks to ensure that there's no recursive zipping of the zipfile itself, and no unnecessarily deep folder structures.

    import os
    import zipfile
    
    def zipdir(path, ziph, ignored_directories, ignored_files):
        # ziph is zipfile handle
        for root, dirs, files in os.walk(path):
          for file in files:
            if not any(ignored_dir in root for ignored_dir in ignored_directories):
              if not any(ignored_fname in file for ignored_fname in ignored_files):
                ziph.write(os.path.join(root, file))
    
    # current working directory
    this_dir = os.path.dirname(os.path.abspath(__file__))
    
    # the directory within the working directory the zip will be created in (build/archives).
    zip_dest_dir = os.path.join('build', 'archives')
    
    # verify zip_dest_dir exists: if not, create it
    if not os.path.isdir(zip_dest_dir):
        os.makedirs(zip_dest_dir, exist_ok=True)
    
    # leave zip_dest_dir blank (or set dist_dir = this_dir) if you want the zip file in the working directory (same directory as the script)
    dest_dir = os.path.join(this_dir, zip_dest_dir)
    
    # name the zip file: remember the file extension
    zip_filename = 'zipped_directory.zip'
    
    # zip file's path
    zip_path = os.path.join(dest_dir, zip_filename)
    
    # create the zipfile handle: you can change ZIP_STORED to any other compression algorithm of your choice, like ZIP_DEFLATED, if you need actual compression
    zipf = zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_STORED)
    
    # ignored files and directories: I personally wanted to ignore the "build" directory, alongside with "node_modules", so those would be listed here.
    ignored_dirs = []
    
    # ignore any specific files: in my case, I was ignoring the script itself, so I'd include 'deploy.py' here
    ignored_files = [zip_filename]
    
    # zip directory contents
    zipdir('.', zipf, ignored_dirs, ignored_files)
    zipf.close()
    

    The resulting zip file should only include directories starting from the working directory: so no Users/user/Desktop/code/.../working_directory/.../etc. kind of file structure.

提交回复
热议问题