【发布时间】:2020-02-24 11:42:07
【问题描述】:
我用 Python 编写了一个脚本,它将从特定目录中删除具有特定扩展名的文件。但我想知道删除了哪些文件,它们的名称应该存储在日志文件或 .txt 文件中。
例如我在'C:\SampleFolder' 位置有一个文件a.log 和b.log,我正在使用以下脚本从该文件夹中删除这两个文件。所以他们的名字'a.log' 和'b.log' 应该与日期和时间一起存储在'delete.log' 文件中。
我必须在我的代码中进行哪些修改,或者我应该为此目的使用哪个函数或库?
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
【问题讨论】:
-
您需要打开日志文件进行写入,然后将每个已删除文件的名称和时间戳信息写入其中。抱歉,SO 不是代码编写服务……
-
每个已删除的文件在
for循环内的file(以及file_full_path)中都有其名称。os.stat()有它的时间戳。
标签: python automation