Python deletes 2 script shares for expired files in a specified directory

Source: Internet
Author: User
Script 1:

These two days wrote in Python a script that deletes the expiration time in the specified directory. Or maybe I'm a beginner of python, not familiar with Python, and always feel that this script should be simpler and easier to write with the shell.
Functionally, the script has achieved the effect I want, but the script is not universal enough, and there are many more areas to be perfected. The script is currently running well under python2.4. At the same time, I added the script to the Python version of the judgment, in theory 2.7 should also be able to use normal. Friends with environment can help with the test.
The script is not perfect in that it can only support file deletion in the first level directory, and does not support directory recursion. At the same time, the definition of outdated files can only be done by week.

Python code:
Copy the Code code as follows:


#! /usr/bin/env python
#-*-Coding=utf-8-*-
Import Sys
Import OS
Import Time,datetime

# define the directory where files need to be deleted
dir = '/data/webbak/'
# written to log file by deleted file
LogDir = '/var/log '
LogFile = Os.path.join (LogDir, ' Delete.log ')

# get current system Python version
ver = sys.version
ver = Ver.split (")
ver = ver[0]

# time to convert "Wed Jul 4 13:25:59 2012" to "2012-07-02 14:50:15" format
# version is the current system Python version number
# time is "Wed Jul 4 13:25:59 2012" format
# The function returned the time of "2012-07-02 14:50:15" format
def string2time (str_time, Version = ver):
version_l = Version.split ('. ') [0:2]
ver = version_l[0] + '. ' + version_l[1]
if (ver = = ' 2.7 '):
F_time = Datetime.datetime.strptime (Str_time, Time_format)
F_time = F_time.strftime ('%y-%m-%d%h:%m:%s ')
Return F_time
elif (ver = = ' 2.4 '):
F_time = Time.strptime (Str_time, Time_format)
F_time = Datetime.datetime (*f_time[0:6])
Return F_time

# time Format
Time_format = "%a%b%d%h:%m:%s%Y"
# Get current time
Today = Datetime.datetime.now ()
# definition 4 weeks
Four_weeks = Datetime.timedelta (weeks=6)
# 4 weeks ago Date
Four_weeks_ago = Today-four_weeks
# Turn the time into timestamps
Four_weeks_ago_timestamps = Time.mktime (Four_weeks_ago.timetuple ())
# list all files in the directory
Files = Os.listdir (dir)
# Open the file log you want to delete
FH = open (logfile, "w+")
# traverse the file to print out the creation time of the file
For f in Files:
# ignore. Files that begin with
If F.startswith ('. '):
Continue
# Ignore directories in current directory
If Os.path.isdir (Os.path.join (dir,f)):
Continue
# Get file Modify time and convert to timestamp format
File_timestamp = Os.path.getmtime (Os.path.join (dir, f))
File_time_f = String2time (Time.ctime (File_timestamp))
If float (file_timestamp) <= float (four_weeks_ago_timestamps):
Fh.write (today) + "\ T" + str (file_time_f) + "\ T" + os.path.join (dir,f) + "\ n")
Os.remove (Os.path.join (dir,f))
# Close File
Fh.close ()


Script 2:
Implement operations similar to the following shell commands
Copy the Code code as follows:

Find/data/log-ctime +5 | Xargs rm-f


Python code:
Copy CodeThe code is as follows:


Import OS
Import Sys
Import time
Class Deletelog:


def __init__ (self,filename,days):
Self.filename = FileName
Self.days = Days
def delete (self):
If Os.path.isfile (self.filename):
FD = open (Self.filename, ' R ')
While 1:
Buffer = Fd.readline ()
If not buffer:break
If Os.path.isfile (buffer):
Os.remove (buffer)
Fd.close ()
Elif Os.path.isdir (self.filename):
For i in [Os.sep.join ([self.filename,v]) for V in Os.listdir (Self.filename)]:
Print I
If Os.path.isfile (i):
If Self.compare_file_time (i):
Os.remove (i)
Elif Os.path.isdir (i):
Self.filename = i
Self.delete ()
def compare_file_time (self,file):
time_of_last_access = os.path.getatime (file)
Age_in_days = (Time.time ()-time_of_last_access)/(60*60*24)
If Age_in_days > Self.days:
Return True
Return False
if __name__ = = ' __main__ ':
If Len (sys.argv) = = 2:
obj = Deletelog (sys.argv[1],0)
Obj.delete ()
Elif len (sys.argv) = = 3:
obj = Deletelog (Sys.argv[1],int (sys.argv[2]))
Obj.delete ()
Else
Print "Usage:python%s listfilename|dirname [days]"% sys.argv[0]
Sys.exit (1)

  • 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.