带有python子文件夹的ZIP文件夹 [英] ZIP folder with subfolder in python

查看:48
本文介绍了带有python子文件夹的ZIP文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 python 压缩一个包含 .xml 文件和 .fgdb 文件的文件夹.有人可以帮助我吗?我尝试了一些我在互联网上找到的脚本,但总是存在一些技术问题(例如创建一个空的 zip 文件,或者创建 zip 文件我无法打开无权限"等.)

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..)

提前致谢.

推荐答案

使其工作的关键是 os.walk() 函数.这是我过去组装的一个应该可以工作的脚本.如果您有任何例外情况,请告诉我.

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()

这篇关于带有python子文件夹的ZIP文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆