python3 正则查找文件名,(Python)如何搜索目录并查找与正则表达式匹配的文件?...

I recently started getting into Python and i am having a hard time searching through directories and matching files based on a regex that i have created. Basically i want it to scan through all the directories in another directory and find all the files that ends with .zip or .rar or .r01 and then run various commands based on what file it is.

import os, re

rootdir = "/mnt/externa/Torrents/completed"

for subdir, dirs, files in os.walk(rootdir):

if re.search('(w?.zip)|(w?.rar)|(w?.r01)', files):

print "match: " . files

解决方案

import os

import re

rootdir = "/mnt/externa/Torrents/completed"

regex = re.compile('(.*zip$)|(.*rar$)|(.*r01$)')

for root, dirs, files in os.walk(rootdir):

for file in files:

if regex.match(file):

print(file)

CODE BELLOW ANSWERS QUESTION IN FOLLOWING COMMENT

That worked really well, is there a way to do this if match is found on regex group 1 and do this if match is found on regex group 2 etc ? – nillenilsson

import os

import re

regex = re.compile('(.*zip$)|(.*rar$)|(.*r01$)')

rx = '(.*zip$)|(.*rar$)|(.*r01$)'

for root, dirs, files in os.walk("../Documents"):

for file in files:

res = re.match(rx, file)

if res:

if res.group(1):

print("ZIP",file)

if res.group(2):

print("RAR",file)

if res.group(3):

print("R01",file)

It might be possible to do this in a nicer way, but this works.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值