【问题标题】:Renaming log files with Python using wildcard and datetime使用通配符和日期时间使用 Python 重命名日志文件
【发布时间】:2021-10-11 12:39:55
【问题描述】:

我今天正在搜索操作一些日志文件的选项,在对它们执行操作后,我发现 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] 没有这样的文件或目录

【问题讨论】:

  • 你没有使用完整路径

标签: python file logging


【解决方案1】:

您可以使用允许使用通配符的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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-21
    • 2017-08-16
    • 1970-01-01
    • 2018-03-09
    • 1970-01-01
    • 2011-07-11
    • 2013-03-06
    • 1970-01-01
    相关资源
    最近更新 更多