Python备份文件到压缩包

注:部分内容来自书籍或者网络,如有侵权,请联系删除。

#!/usr/bin/python
#-*- coding: UTF-8 -*-
from __future__ import print_function
import os
import fnmatch
import tarfile
import datetime

def is_file_match(filename,patterns):
    for pattern in patterns:
        if fnmatch.fnmatch(filename,pattern):
            return True
    return False

def find_specific_files(path,patterns=['*'],exclude_dirs=[]):
    for dirpath,dirnames,filenames in os.walk(path):
        for filename in filenames:
            if is_file_match(filename,patterns):
                yield os.path.join(dirpath,filename)
        for d in exclude_dirs:
            if d in dirnames:
                dirnames.remove(d)
                
def main():
    patterns = ['*.txt','*.py'] 
    now = datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
    filename = "all_files_{0}.tar.gz".format(now)
    with tarfile.open(filename,'w:gz') as f:
        for item in find_specific_files("/root/Python",patterns):
            f.add(item)
            
if __name__ == '__main__':
    main()


「 文章如果对你有帮助,请点个赞哦^^ 」 

1+