python - 如何使用tarfile实现目录过滤的打包文件
黄舟
黄舟 2017-04-18 09:19:38
[Python讨论组]

如何在不使用python调用shell的情况下,就是不使用subprocess,os.system等调用tar命令情况下,使用python标准库的tarfile实现tar中--exclude的效果,例如:

tar -cvpzf /media/sda7/backup.tgz --exclude=/proc --exclude=/lost+found --exclude=/mnt --exclude=/sys --exclude=/media /

这里对目录/下的/proc/lost+found,/mnt,/sys/media目录进行过滤,并其结果打包在/media/sda7/backup.tgz文件中。
下面的解决方案是可以的,但是对于/home/sky目录下的文件打包就不可以了:

#!/usr/bin/env python

import tarfile

exclude_names = ['build']
def filter_func(tarinfo):
    if tarinfo.name not in exclude_names and tarinfo.isdir():
        return None
    else:
        return tarinfo
t = tarfile.open("backup.tgz", "w:gz")
t.add("/home/sky", filter=filter_func)

比如我在sky目录下有1个build目录,只对其进行打包的话,结果如下:

sky@debian:~$ tar -tvf backup.tgz 

可以发现目录下完全没有文件。

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(2)
大家讲道理

TarFile.add(name, arcname=None, recursive=True, exclude=None, *, filter=None)
Add the file name to the archive. name may be any type of file (directory, fifo, symbolic link, etc.). If given, arcname specifies an alternative name for the file in the archive. Directories are added recursively by default. This can be avoided by setting recursive to False. If exclude is given, it must be a function that takes one filename argument and returns a boolean value. Depending on this value the respective file is either excluded (True) or added (False). If filter is specified it must be a keyword argument. It should be a function that takes a TarInfo object argument and returns the changed TarInfo object. If it instead returns None the TarInfo object will be excluded from the archive. See Examples for an example.

利用filter参数设定filter函数,filter函数接收TarInfo对象,在filter函数内判断tarinfo对象的类型和名字,如果不符合要求就不返回传入的对象。

import tarfile
exclude_names = ['proc', 'lost+found', 'mnt', 'sys', 'media']
def filter_func(tarinfo):
    if tarinfo.name in exclude_names and tarinfo.isdir():
        return None
    else:
        return tarinfo
t = tarfile.open("/media/sda7/backup.tgz", "w:gz")
t.add("/", filter=filter_func)
ringa_lee

Python tarfile and excludes
参考一下。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号