python - 删除具有特定扩展名的文件的脚本问题
问题描述
我编写了以下脚本来删除具有特定扩展名的文件。但是,此脚本会删除扩展名为'.log' or '.txt' or '.css'
.
如果文件扩展名是'.log000123'
or怎么办'.log1234'
,所以这里的扩展名是恒定的,但是在扩展名之后添加了随机数。还可以通过此脚本删除此类文件吗?
脚本中的任何修改或指向包含此类示例的任何网站的链接将不胜感激。
import os, time, sys
folder_path = "C:\SampleFolder"
file_ends_with = ".log"
how_many_days_old_logs_to_remove = 7
now = time.time()
only_files = []
for file in os.listdir(folder_path):
file_full_path = os.path.join(folder_path,file)
if os.path.isfile(file_full_path) and file.endswith(file_ends_with):
#Delete files older than x days
if os.stat(file_full_path).st_mtime < now - how_many_days_old_logs_to_remove * 86400:
os.remove(file_full_path)
print "\n File Removed : " , file_full_path
解决方案
您可以使用正则表达式和os.path.splitext
:
import os
import re
file = "myfile.log123"
pattern = ".log(.*)" # match .log followed by anything
fname, ext = os.path.splitext(file)
# check this condition:
if re.match(pattern, ext):
# do stuff
推荐阅读
- python - 熊猫扭曲 html 表格
- bash - 如何为名称在bash中的变量中的变量赋值?
- android - 如何销毁 CountdownTimer 的实例?
- python-3.x - 如何将 AWS 托管策略附加到 cloudformation 和对流层中的角色
- regex - 匹配 Perl 表达式的正则表达式?
- vector - 如何在不分配内存的情况下从 vec 中变异和删除元素?
- mapbox - Mapbox 挤压在 Android 中显示,但在 iOS 中不显示
- c# - 复制并重命名通配符图像文件c#
- azure-data-factory-2 - 从复制数据活动中的输出数组中提取元素
- c# - 抽象类与空实现方法的继承类案例的设计模式