python - 使用通配符和日期时间使用 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] 没有这样的文件或目录
解决方案
您可以使用glob
which 允许通配符:
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)
推荐阅读
- django - 如何将注册中的自定义字段保存到我的数据库中?(姜戈)
- python - SQL 在文件之间不更新
- racket - 在球拍中向左折叠
- angular - Angular 11 - subscribe() 不会修改带有或不带有 ChangeDetectorRef 的 HTML
- file - PowerBi - Powerquery:如果我们从路径加载的文件夹/文件不存在,请更改路径
- python - 如何本地化为我提供 url 的正确 xpath?
- node.js - 运行 npm start 或 npm run start 命令时遇到错误
- java - 如何打印包含空值的二叉树的级别顺序遍历?爪哇
- python - 登录(django项目)
- python-3.x - TypeError:“模块”对象不可调用 Django 3 渲染函数