我有一个包含csv
个文件的目录,名为reports
我要删除reports
文件夹中超过X天的所有文件.
这样可以很好地删除所有文件:
FileUtils.rm_rf("reports/.", secure: true)
但我想要的过滤器只删除X天数之前的文件.
多么?
我有一个包含csv
个文件的目录,名为reports
我要删除reports
文件夹中超过X天的所有文件.
这样可以很好地删除所有文件:
FileUtils.rm_rf("reports/.", secure: true)
但我想要的过滤器只删除X天数之前的文件.
多么?
您可以列出所有文件名,然后使用File.stat
判断每个文件的修改时间并删除每个文件.
例如,您可以使用以下代码:
# 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