'Function to schedule file deletion after x-hours
I found the below function here and edited it a little to delete my files after 2 hours (checks every 1 minute), I want to use it to clean my server's download directory (Linux) after a certain time.
The strange thing is that it won't delete the manually created files, but as I download the videos using youtube-dl, it immediately deletes them!
I realized that the modified time of these files isn't correct;
I downloaded them yesterday (3/2/2022 20:45), but the modified time in my Windows explorer was (1/17/2022 17:51).
As I don't know how to work with st_mtime & st_ctime to achieve the same result on both Windows and Linux systems, please help me if this function has issues for this purpose, or if you know a better way...
I need a simple elegant function...
Function
import os, time
def RemoveFiles(dir_path, hours):
'''
dir_path: Path where the files are stored (⚠ Change it to your path, e.g. './DLDir').
hours: Delete files older than n hours (e.g. 12).
'''
while True:
# Creates a list containing the name of all files in the directory.
all_files = os.listdir(dir_path)
# Stores the seconds passed since the epoch (For Unix system, January 1, 1970, 00:00:00 at UTC is epoch [the point where time begins]).
now = time.time()
n_hours = hours * 3600
for f in all_files:
# Joins the base path with the file name.
file_path = os.path.join(dir_path, f)
# If the thing in the path is a file and not a directory.
# Dir = F, not F = T, continue.
if not os.path.isfile(file_path):
continue
# stat() returns a stat_result object.
# st_mtime is the time of last modification.
if os.stat(file_path).st_mtime < now - n_hours:
os.remove(file_path)
print(f"♻♻♻ Deleted: ♻♻♻ {f}")
sys_starttime_forsleep = time.time()
# Specify the seconds you want to wait (first argument).
time.sleep(60.0 - ((time.time() - sys_starttime_forsleep) % 60.0))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
