python 项目实战之备份文件夹并且压缩文件夹及下面的文件


 

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 # @Time    : 2019/11/12 14:21
 4 # @Author  : zoulixiang
 5 # @Site    :
 6 # @File    : Rsync_day_tom.py
 7 # @Software: PyCharm
 8 import os
 9 import shutil
10 import datetime
11 import zipfile
12 
13 name = os.getcwd()
14 Dir = os.listdir(name)
15 
16 date_yester = (datetime.datetime.now() + datetime.timedelta(days=-1)).strftime("%Y")
17 
18 date_yesterday = (datetime.datetime.now() + datetime.timedelta(days=-1)).strftime("%Y%m%d")
19 
20 date_yesterday_seven = (datetime.datetime.now() + datetime.timedelta(days=-7)).strftime("%Y%m%d")
21 
22 def zip_ya(start_dir):
23     for dir_path, dir_names, file_names in os.walk(start_dir):
24         f_path = dir_path.replace(start_dir, '')  # 这一句很重要,不replace的话,就从根目录开始复制
25         # print(f_path)
26         f_path = f_path and f_path + os.sep or ''  # 实现当前文件夹以及包含的所有文件的压
27         for filename in file_names:
28             mailtime = os.path.getmtime(os.path.join(dir_path, filename))  # 查找当前文件所有时间
29             mailtdate = datetime.datetime.fromtimestamp(mailtime).strftime('%Y%m%d')  # 格式化转化
30             new_dirs = date_yesterday + '/' + start_dir
31             if mailtdate == date_yesterday:  # 判断昨天的时间
32                 """
33                 判断当前的文件--昨天的日期,移动放到指定的位置(新建一个昨天的目录)
34                 """
35                 if not os.path.exists(new_dirs):
36                     os.makedirs(new_dirs)
37                 if os.path.join(new_dirs, filename):
38                     print("已经移动至目标目录",)
39                 else:
40                     shutil.move(os.path.join(dir_path, filename), new_dirs)
41 
42 def zipDir(dirpath):
43     '''
44     :param dirpath: 目标文件夹路径
45     :return: 无
46     '''
47     z_file = dirpath + date_yesterday + '.zip'
48     zip = zipfile.ZipFile(z_file, 'w', zipfile.ZIP_DEFLATED,allowZip64=True)
49     for path, dirnames, filenames in os.walk(dirpath):
50         # 去掉目标和路径,只对目标文件夹下边的文件及文件夹进行压缩(包括父文件夹本身)
51         this_path = os.path.abspath('.')
52         fpath = path.replace(this_path, '')
53         for filename in filenames:
54             zip.write(os.path.join(path, filename), os.path.join(fpath, filename))
55 
56         if os.path.isdir(path):
57             print("删除成功", path)
58             shutil.rmtree(path)
59     zip.close()
60     return z_file
61 
62 def rm_path(Dir):
63     #print(rmpaths)
64     for j in Dir:
65         if j.strip().startswith(date_yester):
66             print(j)
67             """
68             如果大于七天,则删除
69             """
70             if j < date_yesterday_seven:
71                 print("sss",j)
72                 shutil.rmtree(os.path.join(j))
73 
74 if __name__ == '__main__':
75 
76     dirs = []
77     for i in Dir:
78         if not i.strip().startswith("Rs"):
79             if not i.strip().startswith(date_yester):
80                 dirs.append(i)
81     #移动文件到指定的目录
82     for i in dirs:
83         zip_ya(i)
84 
85     #压缩昨天的文件到指定的目录
86     #windowns
87     paths = "D:\\MATRIX_NETWORK\\test\\%s" % date_yesterday
88     #linux
89     #paths = "/home/log/%s" % date_yesterday
90     path_list = os.listdir(paths)
91     for i in path_list:
92         print(i)
93         zipDir(os.path.join(paths, i))
94 
95     #删除7天前的目录
96     rm_path(Dir)

 

效果展示

 

 

posted @ 2019-11-15 16:28  Mr.zou  阅读(930)  评论(0编辑  收藏  举报