python - 删除所有匹配通配符的最新两个文件
问题描述
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
解决方案
您可以将filelist
usingos.stat(f).st_mtime
作为排序键进行排序:
filelist = sorted(filelist, key=lambda f: os.stat(f).st_mtime)
之后您遍历文件列表,不包括最后两个文件:
for f in filelist[:-2]:
os.remove(f)
推荐阅读
- python - 如何从 Dataframe 向堆积面积图的每个级别添加值?
- charts - x轴上的charts_flutter标签/文本相互重叠
- javascript - 使用 Axios 处理 Laravel 响应错误的最佳实践
- sql - 如何修复 oracle Join 中的“列不明确定义”
- javascript - 无法设置未定义的属性“名称”(Nodejs Graphql)
- java - 如何迭代两个不同的对象列表并根据另一个列表中存在的元素修改一个列表的对象属性
- spring-kafka - Kafka 侦听器在 Spring Kafka 2.2.3.RELEASE 的 Spring Boot 应用程序启动之前变得活跃
- node.js - 电子邮件的基础:在 Inky 和 Inlining 之后添加代码
- r - 以正确的格式在屏幕上呈现 R 中的 excel 工作表
- python - 无法抓取需要使用 Python 登录的网站,beautifulSoup