I\'m trying to write a python script to delete all files in a folder older than X days. This is what I have so far:
import os, time, sys
path = r\"c:\\user
This deletes files older than 60 days.
import os
directory = '/home/coffee/Documents'
os.system("find " + directory + " -mtime +60 -print")
os.system("find " + directory + " -mtime +60 -delete")
would like to add what i came up with to do this task. the function is called in the login process.
def remove_files():
removed=0
path = "desired path"
# Check current working directory.
dir_to_search = os.getcwd()
print "Current working directory %s" % dir_to_search
#compare current to desired directory
if dir_to_search != "full desired path":
# Now change the directory
os.chdir( desired path )
# Check current working directory.
dir_to_search = os.getcwd()
print "Directory changed successfully %s" % dir_to_search
for dirpath, dirnames, filenames in os.walk(dir_to_search):
for file in filenames:
curpath = os.path.join(dirpath, file)
file_modified = datetime.datetime.fromtimestamp(os.path.getmtime(curpath))
if datetime.datetime.now() - file_modified > datetime.timedelta(hours=1):
os.remove(curpath)
removed+=1
print(removed)
os.listdir()
returns a list of bare filenames. These do not have a full path, so you need to combine it with the path of the containing directory. You are doing this when you go to delete the file, but not when you stat
the file (or when you do isfile()
either).
Easiest solution is just to do it once at the top of your loop:
f = os.path.join(path, f)
Now f
is the full path to the file and you just use f
everywhere (change your remove()
call to just use f
too).
A simple python script to remove /logs/ files older than 10 days
#!/usr/bin/python
# run by crontab
# removes any files in /logs/ older than 10 days
import os, sys, time
from subprocess import call
def get_file_directory(file):
return os.path.dirname(os.path.abspath(file))
now = time.time()
cutoff = now - (10 * 86400)
files = os.listdir(os.path.join(get_file_directory(__file__), "logs"))
file_path = os.path.join(get_file_directory(__file__), "logs/")
for xfile in files:
if os.path.isfile(str(file_path) + xfile):
t = os.stat(str(file_path) + xfile)
c = t.st_ctime
# delete file if older than 10 days
if c < cutoff:
os.remove(str(file_path) + xfile)
With __file__
you can replace by your path.