使用通配符和日期时间重命名 Python 的日志文件

Renaming log files with Python using wildcard and datetime

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

试图在我的文件名中加入通配符“*****”,但 Python 似乎无法理解。

我的文件名是:

Application_2021-08-06_hostname_[PID].log

目前我要求 Python 阅读这些应用程序文件,并搜索已定义的 words/phrases 例如“用户已登录”、“用户已断开连接”等。他做得很好.我正在使用 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] No such file or directory

您可以使用允许通配符的 glob

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)