ZIP folder with subfolder in python

我只是一个虾纸丫 提交于 2020-08-19 11:37:33

问题


I need to zip a folder that containts an .xml file and a .fgdb file by using python. Could anyone help me? I tried a few scripts I found on internet but there is always some technical issue (such as creating an empty zip file, or create zip file I cannot open 'no permission' etc..)

Thanks in advance.


回答1:


The key to making it work is the os.walk() function. Here is a script I assembled in the past that should work. Let me know if you get any exceptions.

import zipfile
import os
import sys

def zipfolder(foldername, target_dir):            
    zipobj = zipfile.ZipFile(foldername + '.zip', 'w', zipfile.ZIP_DEFLATED)
    rootlen = len(target_dir) + 1
    for base, dirs, files in os.walk(target_dir):
        for file in files:
            fn = os.path.join(base, file)
            zipobj.write(fn, fn[rootlen:])

zipfolder('thenameofthezipfile', 'thedirectorytobezipped') #insert your variables here
sys.exit()



回答2:


This answer is very helpful, but it took me a moment to fully understand what rootlen was for. This example uses some longer variable names to help teach what exactly is going on here. Also included is a block to validate the zip file is correct.

import os
import zipfile

src_path = os.path.join('/', 'some', 'src', 'path')
archive_name = 'myZipFile.zip'
archive_path = os.path.join('/', 'some', 'path', archive_name)

with zipfile.ZipFile(archive_path, 'w', zipfile.ZIP_DEFLATED) as archive_file:
    for dirpath, dirnames, filenames in os.walk(src_path):
        for filename in filenames:
            file_path = os.path.join(dirpath, filename)
            archive_file_path = os.path.relpath(file_path, src_path)
            archive_file.write(file_path, archive_file_path)

with zipfile.ZipFile(archive_path, 'r') as archive_file:
    bad_file = zipfile.ZipFile.testzip(archive_file)

    if bad_file:
        raise zipfile.BadZipFile(
            'CRC check failed for {} with file {}'.format(archive_path, bad_file))


来源:https://stackoverflow.com/questions/10480440/zip-folder-with-subfolder-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!