Python deletes 2 script shares of expired files in the specified directory

  • 2020-04-02 13:33:40
  • OfStack

Script 1:

These two days, I wrote a script in python to delete the expiration time in the specified directory. It may also be that I am a beginner in python and not familiar with python, so I always think this script should be simpler and easier to write with shell.
Functionally, the script did what I wanted, but it wasn't universal enough, and there was more to be done. The script is currently running fine in python2.4. At the same time, I added a judgment on the python version to the script, and it should work in 2.7. A friend with an environment can help test it.
The script is imperfect in that it can only support file deletion under the first level directory, and does not support directory recursion. Meanwhile, the definition of expired files can only be done according to week.

Python code:


#! /usr/bin/env python
# -*- coding=utf-8 -*-
import sys
import os
import time,datetime

#  Defines the directory where the files need to be deleted 
dir = '/data/webbak/'
#  The deleted file is written to the log file 
logdir = '/var/log'
logfile = os.path.join(logdir, 'delete.log')

#  Get the current system python version 
ver = sys.version
ver = ver.split(' ')
ver = ver[0]

#  will "Wed Jul  4 13:25:59 2012" Format the time to convert to" 2012-07-02 14:50:15 "Format the time 
# version Is the current system python The version number 
# time is "Wed Jul  4 13:25:59 2012" Format time 
#  The function returns "2012-07-02 14:50:15" Format time 
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 the current time 
today = datetime.datetime.now()
#  define 4 A few weeks 
four_weeks = datetime.timedelta(weeks=6)
# 4 The date before Monday 
four_weeks_ago = today - four_weeks
#  Turn time into timestamps
four_weeks_ago_timestamps = time.mktime(four_weeks_ago.timetuple())
#  Lists all files in the directory 
files = os.listdir(dir)
#  Open a log of files to be deleted 
fh = open(logfile, "w+")
#  Walk through the file and print out the creation time of the file 
for f in files:
 #  ignore . Opening file 
 if f.startswith('.'):
  continue
 #  Ignore the directory in the current directory 
 if os.path.isdir(os.path.join(dir,f)):
  continue
 #  documented 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(str(today) + "t" + str(file_time_f) + "t" + os.path.join(dir,f) + "n")
  os.remove(os.path.join(dir,f))
#  Close the file 
fh.close()


Script 2:
Implement operations similar to the following Shell command

find  /data/log -ctime +5 | xargs  rm  -f 

Python code:

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)


Related articles: