我在 EventGhost 中使用 Python 脚本来匹配目录中的特定文件类型,并将它们移动到特定位置,以便其他程序对其执行操作。这是整个脚本:
import shutil
import os
SubFileTypes = ('sub','srt','txt')
ZipFileTypes = ('rar','zip','7z','r0')
MediaFileTypes = ('mkv','avi','mp4','wmv')
DownloadName = ''.join(eg.event.payload)
FileName = os.path.basename(DownloadName)
isFolder = os.path.isdir(DownloadName)
eg.globals.tvzip = 'J:\\DL\\TVzip\\'
eg.globals.tvzipdir = eg.globals.tvzip+FileName+'\\'
eg.globals.tvproc = 'J:\\DL\\TVProc\\'
if isFolder == True:
os.mkdir(eg.globals.tvzipdir)
# print 'I\'m a folder!'
for root, dirs, files in os.walk(DownloadName):
for f in files:
if f.endswith(ZipFileTypes):
#print 'I\'m a zip file!'
shutil.copy(os.path.join(root,f),eg.globals.tvzipdir)
if f.endswith(SubFileTypes) or f.endswith(MediaFileTypes):
#print 'I\'m a subtitle or media file!'
shutil.copy(os.path.join(root,f),eg.globals.tvproc)
elif isFolder == False:
shutil.copy(DownloadName,eg.globals.tvproc)
eg.plugins.EventGhost.DisableItem(XmlIdLink(23))
# print 'I\'m NOT a folder!'
else:
print 'I dont know what I am!'
我遇到的具体问题是我需要能够匹配来自 split-rar 格式的每个 .rX 扩展名。这些扩展名从 r0 开始,可以无限数量结束。它们至少是“r+两位数”(r00、r01、r02 等),但我认为它们可以超过两位数,尽管我并不肯定。
有什么方法可以更改我的 ZipFileTypes 列表以包含这些 split-rar 扩展名?还是有别的办法?
请您参考如下方法:
您可以使用正则表达式来匹配以 .r 后跟任意数字的文件名:
import re
# -snip-
for f in files:
if f.endswith(ZipFileTypes) or re.search(r'\.r\d+$', f):
# do stuff
re.search() 将在字符串中的任何位置查找匹配项,而 re.match() 将查找完整的字符串匹配项。对于这种情况,因为我们只关心文件扩展名,所以我们将使用 re.search()。
正则表达式的结构如下:
\.r- 匹配单个句点,后跟r。要转义的\是必需的,因为.否则表示通配符。\d+- 匹配任意数量的数字。\d代表一个数字,+代表“前面的1+”$- 匹配字符串的结尾。
将它们全部放在 \.r\d+$ 中,您就匹配了一个拆分的 rar 扩展。
