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

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

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

相关标签:
25条回答
  • 2020-11-22 07:47

    Here is a variation on the answer given by Nux that works for me:

    def WriteDirectoryToZipFile( zipHandle, srcPath, zipLocalPath = "", zipOperation = zipfile.ZIP_DEFLATED ):
        basePath = os.path.split( srcPath )[ 0 ]
        for root, dirs, files in os.walk( srcPath ):
            p = os.path.join( zipLocalPath, root [ ( len( basePath ) + 1 ) : ] )
            # add dir
            zipHandle.write( root, p, zipOperation )
            # add files
            for f in files:
                filePath = os.path.join( root, f )
                fileInZipPath = os.path.join( p, f )
                zipHandle.write( filePath, fileInZipPath, zipOperation )
    
    0 讨论(0)
  • 2020-11-22 07:49

    For a concise way to retain the folder hierarchy under the parent directory to be archived:

    import glob
    import zipfile
    
    with zipfile.ZipFile(fp_zip, "w", zipfile.ZIP_DEFLATED) as zipf:
        for fp in glob(os.path.join(parent, "**/*")):
            base = os.path.commonpath([parent, fp])
            zipf.write(fp, arcname=fp.replace(base, ""))
    

    If you want, you could change this to use pathlib for file globbing.

    0 讨论(0)
  • 2020-11-22 07:53

    To give more flexibility, e.g. select directory/file by name use:

    import os
    import zipfile
    
    def zipall(ob, path, rel=""):
        basename = os.path.basename(path)
        if os.path.isdir(path):
            if rel == "":
                rel = basename
            ob.write(path, os.path.join(rel))
            for root, dirs, files in os.walk(path):
                for d in dirs:
                    zipall(ob, os.path.join(root, d), os.path.join(rel, d))
                for f in files:
                    ob.write(os.path.join(root, f), os.path.join(rel, f))
                break
        elif os.path.isfile(path):
            ob.write(path, os.path.join(rel, basename))
        else:
            pass
    

    For a file tree:

    .
    ├── dir
    │   ├── dir2
    │   │   └── file2.txt
    │   ├── dir3
    │   │   └── file3.txt
    │   └── file.txt
    ├── dir4
    │   ├── dir5
    │   └── file4.txt
    ├── listdir.zip
    ├── main.py
    ├── root.txt
    └── selective.zip
    

    You can e.g. select only dir4 and root.txt:

    cwd = os.getcwd()
    files = [os.path.join(cwd, f) for f in ['dir4', 'root.txt']]
    
    with zipfile.ZipFile("selective.zip", "w" ) as myzip:
        for f in files:
            zipall(myzip, f)
    

    Or just listdir in script invocation directory and add everything from there:

    with zipfile.ZipFile("listdir.zip", "w" ) as myzip:
        for f in os.listdir():
            if f == "listdir.zip":
                # Creating a listdir.zip in the same directory
                # will include listdir.zip inside itself, beware of this
                continue
            zipall(myzip, f)
    
    0 讨论(0)
  • 2020-11-22 07:55

    Function to create zip file.

    def CREATEZIPFILE(zipname, path):
        #function to create a zip file
        #Parameters: zipname - name of the zip file; path - name of folder/file to be put in zip file
    
        zipf = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)
        zipf.setpassword(b"password") #if you want to set password to zipfile
    
        #checks if the path is file or directory
        if os.path.isdir(path):
            for files in os.listdir(path):
                zipf.write(os.path.join(path, files), files)
    
        elif os.path.isfile(path):
            zipf.write(os.path.join(path), path)
        zipf.close()
    
    0 讨论(0)
  • 2020-11-22 07:56

    If you want a functionality like the compress folder of any common graphical file manager you can use the following code, it uses the zipfile module. Using this code you will have the zip file with the path as its root folder.

    import os
    import zipfile
    
    def zipdir(path, ziph):
        # Iterate all the directories and files
        for root, dirs, files in os.walk(path):
            # Create a prefix variable with the folder structure inside the path folder. 
            # So if a file is at the path directory will be at the root directory of the zip file
            # so the prefix will be empty. If the file belongs to a containing folder of path folder 
            # then the prefix will be that folder.
            if root.replace(path,'') == '':
                    prefix = ''
            else:
                    # Keep the folder structure after the path folder, append a '/' at the end 
                    # and remome the first character, if it is a '/' in order to have a path like 
                    # folder1/folder2/file.txt
                    prefix = root.replace(path, '') + '/'
                    if (prefix[0] == '/'):
                            prefix = prefix[1:]
            for filename in files:
                    actual_file_path = root + '/' + filename
                    zipped_file_path = prefix + filename
                    zipf.write( actual_file_path, zipped_file_path)
    
    
    zipf = zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED)
    zipdir('/tmp/justtest/', zipf)
    zipf.close()
    
    0 讨论(0)
  • 2020-11-22 07:58
    # import required python modules
    # You have to install zipfile package using pip install
    
    import os,zipfile
    
    # Change the directory where you want your new zip file to be
    
    os.chdir('Type your destination')
    
    # Create a new zipfile ( I called it myfile )
    
    zf = zipfile.ZipFile('myfile.zip','w')
    
    # os.walk gives a directory tree. Access the files using a for loop
    
    for dirnames,folders,files in os.walk('Type your directory'):
        zf.write('Type your Directory')
        for file in files:
            zf.write(os.path.join('Type your directory',file))
    
    0 讨论(0)
提交回复
热议问题