首页 > 解决方案 > 删除具有特定扩展名的文件的脚本问题

问题描述

我编写了以下脚本来删除具有特定扩展名的文件。但是,此脚本会删除扩展名为'.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

标签: pythonautomation

解决方案


您可以使用正则表达式和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

推荐阅读