Python periodically deletes files, organizes folders

Source: Internet
Author: User

1, according to the parameters passed in, the file is located in the directory, matching the regular expression of the file, the number of days to delete, these can be written in the configuration file del_file.conf.

del_file3.py

#!/usr/bin/env python# encoding:gbkimport osimport reimport sysimport timeimport datetimeimport logging#reload (SYS) # Sys.setdefaultencoding (' Utf-8 ') logging.basicconfig (level=logging.                    DEBUG, format= '% (asctime) s% (filename) s[line:% (lineno) -1d]% (levelname) s% (message) s ', Datefmt= '%a,%d%b%Y%h:%m:%s ', filename= ' Myapp.log ', filemode= ' a ') # Logging.deb UG (' This was Debug message ') # Logging.info (' This is Info message ') # logging.warning (' This is warning message ') def find_file (File_dir, file_re= ' data ', expire_time=60): # print sys.getdefaultencoding () if file_re = = ': Logging.error (' F Ile_re is Null,exit ') return None #解决编码问题 #file_dir = File_dir.decode ("Utf-8") #file_re = File_re.decode (" Utf-8 ") logging.info (' Incoming parameter: directory [%s], regular expression [%s], number of days expired [%s] '% (file_dir,file_re,expire_time)) #目录下所有文件 all_file = OS . Listdir (file_dir) #匹配正则的文件 reg_file_list = [] Reg_str = File_re for Reg_fIle in All_file:if Os.path.isdir (reg_file): Continue if Re.match (reg_str,reg_file): l Ogging.info (' regular match to file: [%s] '% reg_file) reg_file_list.append (reg_file) If Len (reg_file_list) < 7:l Ogging.info (' The number of matching files is less than 7, do not delete! ') return None #满足过期时间的文件 #当前时间 today = Datetime.datetime.now () #n天 n_days = Datetime.timedelta (days =int (expire_time)) #n天前日期 N_days_agos = today-n_days #n天前时间戳 n_days_agos_timestamps = Time.mktime (N_days_ago S.timetuple ()) #日期比较 for date_file in reg_file_list:abs_file = Os.path.join (file_dir,date_file) F            Ile_timestamp = Os.path.getmtime (abs_file) if float (file_timestamp) <= float (n_days_agos_timestamps): Logging.info (' Expiration match to file: [%s] '% abs_file) #print "match to File:", Abs_file #删除满足条件的文件 Os.remove (A Bs_file) logging.info (' Delete file: [%s] success '% abs_file) #读取配置文件 def read_conf (File_path): WithOpen (File_path, ' R ') as F:for line in f:line_list = Line.strip (). Split (', ') If Len (line_list )! = 3:logging.warning ('%s line is not configured correctly '% Line.strip ()) Continue file_dir = Line_list [0] file_re= line_list[1] expire_time = line_list[2] Find_file (file_dir,file_re,expire_ti Me) If __name__ = = "__main__": # read_conf (' D:\workspace\myPython\com\del_file.conf ') read_conf (sys.argv[1])

Del_file.conf

C:\Users\Administrator\Desktop\Python Learning \python Test Catalog,. * Data, 30

2, regular collation date files or folders, passed in Parameters: folder directory, matching the regular expression folder, the number of days to organize folders, parameters can be written in the configuration file dir_reg.conf.

move_file.py

#!/usr/bin/env python# encoding:gbkimport osimport reimport sysimport timeimport datetimeimport loggingimport shutil# Reload (SYS) #sys. setdefaultencoding (' Utf-8 ') logging.basicconfig (level=logging.                    DEBUG, format= '% (asctime) s% (filename) s[line:% (lineno) -1d]% (levelname) s% (message) s ', Datefmt= '%a,%d%b%Y%h:%m:%s ', filename= ' D:\\move.log ', filemode= ' a ') # logging. Debug (' This was Debug message ') # Logging.info (' This is Info message ') # logging.warning (' This is warning message ') def Find_f Ile (File_dir, file_re= ' data ', expire_time=60): Logging.info (' incoming parameter: directory [%s], regular expression [%s], number of days expired [%s] '% (file_dir,file_re,expi        Re_time)) If not os.path.exists (File_dir): Logging.info (' incoming parameter: directory [%s] does not exist '% File_dir ') return None #匹配文件或目录 #目录下所有文件 all_file = Os.listdir (file_dir) #匹配正则的文件或目录 reg_file_list = [] Reg_str = File_re for Reg_file in All_file: #if os.path.isdir (reg_file): # contInue if Re.match (reg_str,reg_file): Logging.info (' regular match to file: [%s] '% reg_file) Reg_file_list.app End (Reg_file) If Len (reg_file_list) < 7:logging.info (' the number of matching files is less than 7, no move operation! ') return None #满足过期时间的文件 #当前时间 today = Datetime.datetime.now () #1天前时间 one_days = datetime.t Imedelta (days=1) One_days_agos = today-one_days #1天前时间文件夹 One_days_agos_dir = One_days_agos.strftime ("%Y-%m-%d" ) #1天前时间戳 one_days_agos_timestamps = Time.mktime (One_days_agos.timetuple ()) #n天前时间 n_days = datetime.timed    Elta (Days=int (expire_time)) N_days_agos = today-n_days #n天前时间文件夹 N_days_dir = N_days_agos.strftime ("%y-%m-%d") #n天前时间戳 n_days_agos_timestamps = Time.mktime (N_days_agos.timetuple ()) #新建目录000 -00-00~0000-00-00 date_dir = '%s ' _%s '% (n_days_dir,one_days_agos_dir) if not os.path.exists (Os.path.join (File_dir,date_dir)): Os.mkdir (Os.path.jo In (file_dir,date_dir)) #移动1 file or directory for ~n days for Date_file in reg_file_list:abs_file = os.path.join (file_dir,date_file) File_timestamp = Os.path.getctime (abs_file) If float (n_days_agos_timestamps) <= float (file_timestamp) <= float (one_days_agos_timestamps): Logging . info (' Move file: [%s] '% abs_file) #print "match to File:", Abs_file #移动满足条件的文件 shutil.move (Abs_file, Os.path.join (File_dir,date_dir)) Logging.info (' Move: [%s] to [%s] success '% (Abs_file,os.path.join (file_dir,date_dir))) d EF read_conf (File_path): With open (File_path, ' R ') as F:for line in f:line_list = Line.strip (). Split (', ') If Len (line_list)! = 3:logging.warning ('%s line is not configured correctly '% Line.strip ()) Continu E File_dir = line_list[0] file_re= line_list[1] expire_time = line_list[2] Fin D_file (file_dir,file_re,expire_time) If __name__ = = "__main__": read_conf (Sys.argv[1])

dir_reg.conf

d:\mylog,^\d{4}-\d{2}-\d{2}$,30d:\mylog,^\d{4}-\d{2}-\d{2}$,90

Python periodically deletes files, organizes folders

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.