忽略具有特定文件类型的文件夹

时间:2011-01-01 16:34:03

标签: python powershell

我徒劳地试图重写我在这里找到的旧Powershell脚本 - "$_.extension -eq" not working as intended? - 对于Python。我没有Python经验或知识,我的“脚本”很乱,但它主要起作用。唯一缺少的是我希望能够忽略不包含“mp3s”的文件夹,或者我指定的任何文件类型。这是我到目前为止所拥有的 -

import os, os.path, fnmatch

path = raw_input("Path :  ")

for filename in os.listdir(path):
if os.path.isdir(filename):
    os.chdir(filename)
    j = os.path.abspath(os.getcwd())
    mp3s = fnmatch.filter(os.listdir(j), '*.mp3')
    if mp3s:
        target = open("pls.m3u", 'w')
        for filename in mp3s:
            target.write(filename)
            target.write("\n")
    os.chdir(path)

我希望能够做的(如果可能的话)是当脚本循环遍历文件夹时忽略那些不包含'mp3s'的文件夹,并删除'pls.m3u'。如果我默认创建'pls.m3u',我只能使脚本正常工作。问题是,在文件夹中创建了大量空的'pls.m3u'文件,例如只包含'.jpg'文件。你明白了。

我确信这个脚本对Python用户来说是亵渎神明的,但任何帮助都会非常感激。

2 个答案:

答案 0 :(得分:2)

如果我理解正确,你的核心问题是这个脚本正在创建很多空的pls.m3u文件。那是因为你甚至在检查是否有任何想要写的内容之前打电话给open

一个简单的解决方法是改变这个:

target = open("pls.m3u", 'w')
j = os.path.abspath(os.getcwd())
for filename in os.listdir(j):
    (title, extn) = os.path.splitext(filename)
    if extn == ".mp3":
        target.write(filename)
        target.write("\n")

进入这个:

target = None
j = os.path.abspath(os.getcwd())
for filename in os.listdir(j):
    (title, extn) = os.path.splitext(filename)
    if extn == ".mp3":
        if not target:
            target = open("pls.m3u", 'w')
        target.write(filename)
        target.write("\n")
if target:
    target.write("\n")
    target.write("\n")

也就是说,只有在我们第一次决定写入文件时才打开文件。

更多Pythonic方法可能是做这样的事情:

j = os.path.abspath(os.getcwd())
mp3s = [filename for filename in os.listdir(j)
        if os.path.splitext(filename)[1] == ".mp3"]
if mp3s:
    target = open("pls.m3u", 'w')
    for filename in mp3s:
        target.write(filename)
        target.write("\n")
    target.write("\n")
    target.write("\n")

也就是说,首先在内存中创建一个mp3列表(在这里使用列表推导,但如果你对它更熟悉的话可以使用普通的旧for循环和append)然后仅在结果列表非空时才打开文件。 (如果非空,则列表是真实的)

答案 1 :(得分:0)

我认为你可以采用两级方法。首先,将toplevel目录复制到另一个目录,忽略不包含mp3文件的目录。

import shutil
IGNORE_PATTERNS = ('*mp3s')
shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=shutil.ignore_patterns(IGNORE_PATTERNS))

然后继续使用您在示例代码中为文件执行的方法。请注意,shutil.copytree只有来自python2.5

的ignore_patterns