#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#################################################################
#Describe:查找path1目录中N天之前的文件并备份到path2目录
#Date:2018-12-17
#Usage:1.py path1 path2 days
#################################################################
import os
import sys
import time
import tarfile
import shutil
parms=sys.argv
if len(parms[1:])<>3:
print "Error:it needs three parms"
exit('Exit')
if not os.path.isdir(parms[1]):
print("Error:there is no such directory: "+path1)
exit("Exit")
try:
f=float(parms[3])
except ValueError:
# print 'The third parm is not digit;Exit'
exit('The third parm is not digit;Exit')
path1=parms[1]
path2=parms[2]
days=float(parms[3])
def bak(file1):
now=time.strftime('%Y%m%d')
tarname='.'.join([file1,now,'bak.tar'])
with tarfile.open(tarname,mode='w') as tar:
tar.add(file1)
if path1!=path2:
if os.path.isdir(path2):
if os.path.isfile(tarname):
shutil.move(tarname,path2)
else:
print tarname
else:
if os.path.isfile(tarname):
print("there is no such directory: "+path2+"; it will make a directory named "+path2)
os.mkdir(path2)
shutil.move(tarname,path2)
else:
print tarname
os.chdir(path1)
for filename in os.listdir(path1):
file_modify=os.path.getmtime(filename)
file_now=time.time()
days1=(file_now-file_modify)/3600/24
if (days1>days):
bak(filename)
else:
print(filename)
脚本参数用法,使用异常处理来判断参数是否数字,tarfile用法,time用法