本帖最后由 Cool_Breeze 于 2021-1-23 14:34 编辑
# 被打包的文件日期,指的是文件最后修改日期# 增量打包需要安装rar
# shutil 打包需要复制文件到指定目录,然后在打包
[Python] 纯文本查看 复制代码 # coding=utf-8
# python3.7.9
import os
import time
import shutil
import configparser
from threading import Thread
from queue import Queue
from subprocess import run
class zipConfig(object):
def __init__(self, configName):
try:
self.config = configparser.ConfigParser()
self.config.read(configName)
self.zipRoot = self.config['shutil']['root'] # 打包父目录
self.zipBase = self.config['shutil']['base'] # 指定打包的子目录
self.zipName = self.config['shutil']['name'] # 打包文件名
self.zipF = self.config['shutil']['format'] # 打包文件格式 zip
self.zipSD = self.config['shutil']['sdate'] # 起始日期
self.zipED = self.config['shutil']['edate'] # 结束日期
self.zipFD = self.config['shutil']['dirname'] # 把符合要求的文件复制到这个目录
self.zipSrc = self.config['shutil']['dir'] # 待处理目录
self.zipRarPro = self.config['rarexe']['rar'] # RaR程序的绝对路径名
self.zipRarName = self.config['rarexe']['name'] # RaR打包后的文件名
self.zipshutil = self.config.getboolean('rarexe','shutil') # 是否使用shutil打包文件
# 将日期转换为时间戳
self.sTimestamp = time.mktime(time.strptime(self.zipSD,'%Y-%m-%d'))
self.eTimestamp = time.mktime(time.strptime(self.zipED,'%Y-%m-%d'))
except Exception as err:
print(err)
raise
# shutil 复制一个文件
def shutilCopyFile(queue):
global zipc
while True:
data = queue.get()
if data is None: break
print(f'正在复制文件 {data}')
shutil.copy(data, zipc.zipFD)
exit(0)
# rar 增量打包文件
def rar(queue, fileName):
global zipc
while True:
data = queue.get()
if data is None: break
cmd = f'{zipc.zipRarPro} -ep -y a {fileName} {data}'
if run(cmd).returncode == 0:
print(f'添加成功 {data}')
else: print(f'添加失败 {data}')
exit(0)
# 过滤不满足要求的文件
def filterFile(zipc):
queue = Queue()
if zipc.zipshutil:
if not os.path.exists(zipc.zipFD): os.mkdir(zipc.zipFD)
t = Thread(target=shutilCopyFile, args=(queue,))
else:
t = Thread(target=rar, args=(queue, zipc.zipRarName))
t.start()
# 遍历文件目录
for dirPath, dirNames, fileNames in os.walk(zipc.zipSrc):
for file in fileNames:
src = os.path.join(dirPath,file)
# 获取文件最后修改时间 getmtime
# 获取文件最后访问时间 getatime
# 获取文件创建时间win getctime
if zipc.sTimestamp < os.path.getmtime(src) < zipc.eTimestamp:
queue.put(src)
# 退出子线程
queue.put(None)
t.join()
if zipc.zipshutil:
print('正在打包文件')
# shutil 打包文件
print(shutil.make_archive(zipc.zipName, zipc.zipF, zipc.zipRoot, zipc.zipBase))
# 删除复制的文件
shutil.rmtree(zipc.zipFD)
if __name__ == '__main__':
zipc = zipConfig('zip.ini')
filterFile(zipc)
配置文件 zip.ini :
[Python] 纯文本查看 复制代码 [DEFAULT]
# 调用shutil打包
shutil = true
# 待处理目录
dir = D:\GIN\py\sorting_method
# 起始日期
sdate = 2020-12-1
# 结束日期
edate = 2020-12-31
[rarexe]
# 文件名
# name = d:\gin\cool
name = cool.zip
rar = C:\Program Files\WinRAR\winrar.exe
[shutil]
# 打包父目录
root = ./
# 打包文件格式 zip
format = zip
name = cool
# 指定打包的子目录
base = ./filterTemp
# 把符合要求的文件复制到这个目录
dirname = filterTemp |