仅压缩目录的内容,排除父目录 - Python [英] ZIp only contents of directory, exclude parent - Python

查看:38
本文介绍了仅压缩目录的内容,排除父目录 - Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试压缩目录的内容,而不压缩目录本身,但是我找不到明显的方法来做到这一点,而且我对 python 非常陌生,所以它对我来说基本上是德语.这是我正在使用的代码,它成功地包含了父级和内容:

I'm trying to zip the contents of a directory, without zipping the directory itself, however I can't find an obvious way to do this, and I'm extremely new to python so it's basically german to me. here's the code I'm using which successfully includes the parent as well as the contents:

#!/usr/bin/env python
import os
import zipfile

def zipdir(path, ziph):
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
        for file in files:
            ziph.write(os.path.join(root, file))

if __name__ == '__main__':
    zipf = zipfile.ZipFile('Testing.zip', 'w', zipfile.ZIP_DEFLATED)
    zipdir('android', zipf)
    zipf.close()

我试过修改它,但总是以难以理解的错误告终.任何帮助将不胜感激.

I've tried modifying it, but always end up with incomprehensible errors. Any help would be greatly appreciated.

推荐答案

write 有第二个参数 - 存档中的名称,即.

write has second argument - name in archive, ie.

ziph.write(os.path.join(root, file), file)


#!/usr/bin/env python
import os
import zipfile

def zipdir(path, ziph):
    length = len(path)
    
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
        folder = root[length:] # path without "parent"
        for file in files:
            ziph.write(os.path.join(root, file), os.path.join(folder, file))

if __name__ == '__main__':
    zipf = zipfile.ZipFile('Testing.zip', 'w', zipfile.ZIP_DEFLATED)
    zipdir('android', zipf)
    zipf.close()


Pathlib 解决方案

from pathlib import Path 

def zipdir(parent_dir : str , ziph : ZipFile) -> None:
    
    for file in Path(parent_dir).rglob('*'): # gets all child items
        ziph.write(file, file.name) 

这篇关于仅压缩目录的内容,排除父目录 - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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