SoFunction
Updated on 2024-11-15

Python Delete Expired Files in a Specified Directory 2 Scripts to Share


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

# Define the directory where the files need to be deleted
dir = '/data/webbak/'
# Deleted files written to log files
logdir = '/var/log'
logfile = (logdir, '')

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

# Convert the time in the format "Wed Jul 4 13:25:59 2012" to the time in the format "2012-07-02 14:50:15".
# version is the current system python version.
# time is in the format "Wed Jul 4 13:25:59 2012".
# function returns the time in "2012-07-02 14:50:15" format
def string2time(str_time, version = ver):
 version_l = ('.')[0:2]
 ver = version_l[0] + '.' + version_l[1] 
 if (ver == '2.7'):
  f_time = (str_time, time_format)
  f_time = f_time.strftime('%Y-%m-%d %H:%M:%S')
  return f_time
 elif(ver == '2.4'):
  f_time = (str_time, time_format)
  f_time = (*f_time[0:6])
  return f_time

# Time format
time_format = "%a %b %d %H:%M:%S %Y"
# Get the current time
today = ()
# Define 4 weeks
four_weeks = (weeks=6)
# Date 4 weeks ago
four_weeks_ago = today - four_weeks
# Convert time to timestamps
four_weeks_ago_timestamps = (four_weeks_ago.timetuple())
# List all files in the directory
files = (dir)
# Open the log of files to be deleted
fh = open(logfile, "w+")
# Iterate through the file and print out the creation time of the file
for f in files:
# Ignore the . files that begin with .
 if ('.'):
  continue
# Ignore directories in the current directory
 if ((dir,f)):
  continue
# Get the modify time of the file and convert it to timestamp format
 file_timestamp = ((dir, f))
 file_time_f = string2time((file_timestamp))
 if float(file_timestamp) <= float(four_weeks_ago_timestamps):
  (str(today) + "\t" + str(file_time_f) + "\t" + (dir,f) + "\n")
  ((dir,f))
# Close the file
()