I have a directory of csv
files called reports
I want to delete all files from the reports
folder that are older than X number of days.
This works great to remove ALL files:
FileUtils.rm_rf("reports/.", secure: true)
But I want the filter of only remove files older than X number of days.
How?
You can list all file names, then use File.stat
to check the modification time of each file and remove each one of them.
For instance, you could use the following code:
# will count X days older than "reference_time"
reference_time = Time.now
# use the following value to delete files older than 30 days
delete_older_than = 30 * (24 * 3600) # value in seconds
all_files = Dir['reports/*']
all_files.each do |relative_file_name|
# not really necessary, but I like to work with full file paths
file_path = File.expand_path(relative_file_name)
# if you want to be strict and delete only files (e.g. not folders),
# this line skips any non-files.
next unless File.file?(file_path)
st = File.stat(file_path)
# modification time is at st.mtime
if st.mtime < (reference_time - delete_older_than)
File.unlink(file_path)
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With