首页 > 解决方案 > 删除所有匹配通配符的最新两个文件

问题描述

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

我可以通过上面的代码删除所有文件。但我不想从 10 个 txt 文件中删除最新的 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

标签: pythondelete-file

解决方案


您可以将filelistusingos.stat(f).st_mtime作为排序键进行排序:

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

之后您遍历文件列表,不包括最后两个文件:

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

推荐阅读