<p>只需使用<em>any</em>来查看是否有任何文件以<code>.mkv</code>结尾,在进一步操作之前,您还可以简化为<em>if/else</em>,就像对最后两个匹配项一样。同时使用<a href="https://docs.python.org/2/library/subprocess.html#subprocess.check_call" rel="nofollow">subprocess.check_call</a>将是一种更好的方法:</p>
<pre><code>import os
import re
from subprocess import check_call
from os.path import join
rx = '(.*zip$)|(.*rar$)|(.*r00$)'
path = "/mnt/externa/folder"
for root, dirs, files in os.walk(path):
if not any(f.endswith(".mkv") for f in files):
for file in files:
res = re.match(rx, file)
if res:
# use os.path.join
pth = join(root, file)
# it can only be res.group(1) or one of the other two so we only need if/else.
if res.group(1):
print("Unzipping ",file, "...")
check_call(["unzip" , pth, "-d", root])
else:
check_call(["unrar","e", pth, root])
</code></pre>
<p>你也可以忘记雷克斯,只需使用if/elif和结构端部公司名称:</p>
^{pr2}$
<p>如果您真正关心的是不重复步骤和速度,那么可以在迭代时进行筛选,也可以在检查.mkv时通过切片进行扩展收集,并使用for/else逻辑:</p>
<pre><code>good = {"rar", "zip", "r00"}
for root, dirs, files in os.walk(path):
if not any(f.endswith(".mkv") for f in files):
tmp = {"rar": [], "zip": []}
for file in files:
ext = file[-4:]
if ext == ".mkv":
break
elif ext in good:
tmp[ext].append(join(root, file))
else:
for p in tmp.get(".zip", []):
print("Unzipping ", p, "...")
check_call(["unzip", p, "-d", root])
for p in tmp.get(".rar", []):
check_call(["unrar", "e", p, root])
</code></pre>
<p>这将使<code>.mkv</code>的任何匹配短路,或者只迭代<code>.rar</code>或{<cd4>}的任何匹配,但除非您真正关心效率,否则我将使用第二种逻辑。在</p>
<p>为了避免覆盖,可以使用计数器将每个目录解压缩到新的子目录中,以帮助创建新的目录名:</p>
<pre><code>from itertools import count
for root, dirs, files in os.walk(path):
if not any(f.endswith(".mkv") for f in files):
counter = count()
for file in files:
pth = join(root, file)
if file.endswith("zip"):
p = join(root, "sub_{}".format(next(counter)))
os.mkdir(p)
print("Unzipping ",file, "...")
check_call(["unzip" , pth, "-d", p])
elif file.endswith((".rar",".r00")):
p = join(root, "sub_{}".format(next(counter)))
os.mkdir(p)
check_call(["unrar","e", pth, p])
</code></pre>
<p>每个都将被解压到根目录下的一个新目录中,即<code>root_path/sub_1</code>等。。在</p>
<p>您最好在问题中添加一个示例,但如果真正的问题是您只需要.rar或.r00中的一个,则可以在找到.rar或.r00的任何匹配项时设置一个标志,并且只有在未设置标志时才可以解包:</p>
<pre><code>for root, dirs, files in os.walk(path):
if not any(f.endswith(".mkv") for f in files):
found_r = False
for file in files:
pth = join(root, file)
if file.endswith("zip"):
print("Unzipping ",file, "...")
check_call(["unzip", pth, "-d", root])
found_zip = True
elif not found_r and file.endswith((".rar",".r00"))
check_call(["unrar","e", pth, root])
found_r = True
</code></pre>
<p>如果也只有一个zip,则可以设置两个标志,并在设置了这两个标志的地方退出循环。在</p>