删除文件夹中的所有文件,但最后一个吗? [英] Delete all files inside a folder but the last?
问题描述
我正在寻找一个脚本来循环遍历一个文件夹并删除其中的所有文件,但最后一个是最新的(我已将每个文件的名称标记为 filename_date('Y' )_date('m')_ date('d')。extension)
,不确定是否相关)。
I'm looking for a script to loop through a folder and delete all the files inside it but the last, most recent one ( I have marked the name of each file as filename_date('Y')_date('m')_date('d').extension)
, not sure if relevant ).
我找到了此脚本在堆栈上:
I have found this script here on stack:
if ($handle = opendir('/path/to/your/folder'))
{
$files = array();
while (false !== ($file = readdir($handle)))
{
if (!is_dir($file))
{
// You'll want to check the return value here rather than just blindly adding to the array
$files[$file] = filemtime($file);
}
}
// Now sort by timestamp (just an integer) from oldest to newest
asort($files, SORT_NUMERIC);
// Loop over all but the 5 newest files and delete them
// Only need the array keys (filenames) since we don't care about timestamps now as the array will be in order
$files = array_keys($files);
for ($i = 0; $i < (count($files) - 5); $i++)
{
// You'll probably want to check the return value of this too
unlink($files[$i]);
}
}
以上删除了除最后五个以外的任何内容。这是一个好方法吗?还是有另一种方法,更简单或更更好?
This above deletes anything but the last five. Is this a good way to do it ? Or is there another way, simpler or better one ?
推荐答案
那行得通。我认为没有比这更简单的方法了。另外,您的解决方案实际上非常简单。
That works. I don't believe there's a simpler way to do it. Plus, your solution is actually quite simple.
这篇关于删除文件夹中的所有文件,但最后一个吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!