在python上匹配文件名

2024-06-28 10:51:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个文件夹中有多个文件,其中一些文件名为'网络日志,而其他的则被命名为网络-wTHz.log文件. 连字符后面的最后四个字符一直在变化。我可以给出什么通配符来匹配这两个文件?我使用以下if语句:

if current_file == 'network.log' or current_file == 'network-*.log':
     curr_file_path = dir_path + str('/') + str(current_file)

上面的代码工作正常,但它只查找网络日志. 找不到任何有网络模式的文件-xxxx.日志. 你知道吗


Tags: 文件path网络文件夹logif文件名network
3条回答
if current_file.startswith('network') and current_file.endswith('.log')

使用glob,它是为这些东西设计的:

import glob

for file_with_path in glob.iglob('/path/to/directory/network*.log'):
    print(file_with_path)

使用正则表达式。你知道吗

import re  
if re.match("^network(-.*).log$", current_file):
    ....

相关问题 更多 >