删除除最新的两个匹配通配符的文件外的所有文件

Delete all but latest two files matching wildcard

import glob
import os
filelist=glob.glob("/home/test/*.txt")
for file in filelist:
  os.remove(file)

我可以通过上面的代码删除所有文件。但我不想删除 10 个 txt files.Rest 中的最新 2 个文件。 有人可以帮我吗?

编辑:

我尝试 index 排除最后 2 个文件,得到不同的输出。文件

-rwxrwxr-x 1 test1 test 14 May 27 2015 test.txt 
-rw-r--r-- 1 test1 test 1857 Nov 9 2016 list.txt 
-rw-r--r-- 1 test1 test 140 Jun 8 22:09 check.txt 
-rw-r--r-- 1 test1 test 570 Jun 8 22:12 ert.txt 
-rw-r--r-- 1 test1 test 0 Jul 2 03:17 1.txt 
-rw-r--r-- 1 test1 test 0 Jul 2 03:17 2.txt 

我的新密码是:

import glob import os 
filelist=glob.glob("/home/test/*.txt") 
for file in filelist[:-2]: 
    print file 

输出

> /home/test/1.txt 
> /home/test/2.txt
> /home/test/list.txt  
> /home/test/ert.txt

您可以使用 os.stat(f).st_mtime 作为排序键对 filelist 进行排序:

filelist = sorted(filelist, key=lambda f: os.stat(f).st_mtime)

然后迭代文件列表,排除最后两个文件:

for f in filelist[:-2]:
    os.remove(f)

如果您想排除 glob 机器中的最后 2 个项目,只需更改您的 for 循环:

import glob
import os
filelist=glob.glob("/home/test/*.txt")
for file in filelist[:-2]:
  os.remove(file)

否则您可以使用其他答案对文件进行排序并排除最后 2 个文件。

编辑:

python 2 glob

The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, although results are returned in arbitrary order.

也看看这个:

How is Pythons glob.glob ordered?