首页 > 解决方案 > 使用通配符和日期时间使用 Python 重命名日志文件

问题描述

我今天正在搜索操作一些日志文件的选项,在对它们执行操作后,我发现 Python 在导入 os 模块后具有 os.rename 资源,但我对正则表达式有一些疑问。

试图在我的文件名上加上通配符“*****”,但 Python 似乎不理解它。

我的文件名是:

Application_2021-08-06_hostname_[ PID ].log

目前,我要求 Python 读取这些应用程序文件,并搜索已定义的单词/短语,例如“用户已登录”、“用户已断开连接”等。他做得很好。我正在使用 datetime 模块,因此 Python 将始终仅读取当前文件。

但是我现在要做的是在 Python 读取文件并执行某些操作之后更改文件的名称。所以当他发现“Today's sessions are done”时,他会将文件名改为:

Application_06-08-2021_hostname_[ PID ].log

因为以后操作起来会更容易..

考虑到 [ PID ] 总是会改变,这是我想设置通配符的部分,因为它可以是 56、142、3356、74567 或任何值。

使用 os.rename 模块,我遇到了一些错误。你有什么建议?

代码

import os
import time
from datetime import datetime

path = '/users/application/logs'

file_name = 'Application_%s_hostname_'% datetime.now().strftime('%Y-%m-%d')
new_file_name = 'Application_%s_hostname_'% datetime.now().strftime('%d-%m-%Y')

os.rename(file_name, new_file_name)

错误是:

OSError: [Errno 2] 没有这样的文件或目录

标签: pythonfilelogging

解决方案


您可以使用globwhich 允许通配符:

import glob, os
from datetime import datetime
current_date = datetime.now()
path = '/users/application/logs'
# note the use of * as wild card
filename ='Application_%s_hostname_*'% current_date.strftime('%Y-%m-%d')
full_path = os.path.join(path, filename)
replace_file = glob.glob(full_path)[0]  # will return a list so take first element
# or loop to get all files
new_name = replace_file.replace(  current_date.strftime('%Y-%m-%d'),  current_date.strftime('%d-%m-%Y') )
os.rename(replace_file, new_name)

推荐阅读