【发布时间】:2016-09-06 19:52:24
【问题描述】:
我一直在编写一个脚本,该脚本将检查目录中的每个子目录并使用正则表达式匹配文件,然后根据文件的类型使用不同的命令。
所以我完成的是基于正则表达式匹配的不同命令的使用。现在它会检查 .zip 文件、.rar 文件或 .r00 文件,并为每个匹配项使用不同的命令。但是我需要帮助遍历每个目录并首先检查那里是否有 .mkv 文件,然后它应该只是传递该目录并跳转到下一个,但如果有匹配,它应该运行命令,然后当它完成继续下一个目录。
import os
import re
rx = '(.*zip$)|(.*rar$)|(.*r00$)'
path = "/mnt/externa/folder"
for root, dirs, files in os.walk(path):
for file in files:
res = re.match(rx, file)
if res:
if res.group(1):
print("Unzipping ",file, "...")
os.system("unzip " + root + "/" + file + " -d " + root)
elif res.group(2):
os.system("unrar e " + root + "/" + file + " " + root)
if res.group(3):
print("Unraring ",file, "...")
os.system("unrar e " + root + "/" + file + " " + root)
编辑:
这是我现在拥有的代码:
import os
import re
from subprocess import check_call
from os.path import join
rx = '(.*zip$)|(.*rar$)|(.*r00$)'
path = "/mnt/externa/Torrents/completed/test"
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)
try:
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","-o-", pth, root,])
found_r = True
break
except ValueError:
print ("Oops! That did not work")
这个脚本工作正常,但有时当文件夹中有 Subs 时我似乎遇到了问题,这是我在运行脚本时收到的错误消息:
$ python unrarscript.py
UNRAR 5.30 beta 2 freeware Copyright (c) 1993-2015 Alexander Roshal
Extracting from /mnt/externa/Torrents/completed/test/The.Conjuring.2013.1080p.BluRay.x264-ALLiANCE/Subs/the.conjuring.2013.1080p.bluray.x264-alliance.subs.rar
No files to extract
Traceback (most recent call last):
File "unrarscript.py", line 19, in <module>
check_call(["unrar","e","-o-", pth, root])
File "/usr/lib/python2.7/subprocess.py", line 541, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['unrar', 'e', '-o-', '/mnt/externa/Torrents/completed/test/The.Conjuring.2013.1080p.BluRay.x264-ALLiANCE/Subs/the.conjuring.2013.1080p.bluray.x264-alliance.subs.rar', '/mnt/externa/Torrents/completed/test/The.Conjuring.2013.1080p.BluRay.x264-ALLiANCE/Subs']' returned non-zero exit status 10
我无法真正理解代码有什么问题,所以我希望你们中的一些人愿意帮助我。
【问题讨论】:
-
Python 对缩进很敏感,因此您的代码不会像您发布的那样工作。我已经为你固定了间距。