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

1 投票
2 回答
712 浏览
提问于 2025-04-16 09:16

我正在努力把我以前的Powershell脚本改写成Python,链接在这里 - "$_.extension -eq" 的问题。我对Python没有任何经验或知识,我的“脚本”一团糟,但大部分功能都能正常工作。现在缺少的就是我想忽略那些不包含“mp3”文件的文件夹,或者我指定的其他文件类型。以下是我目前的代码 -

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)

我希望能做到的就是,当脚本在遍历文件夹时,能够忽略那些不包含“mp3”的文件夹,并且删除“pls.m3u”文件。我发现只有在默认创建“pls.m3u”的情况下,脚本才能正常工作。问题是,这样会在只包含“.jpg”文件的文件夹中产生很多空的“pls.m3u”文件。你明白我的意思了。

我知道这个脚本可能让Python用户感到不满,但任何帮助都将非常感激。

2 个回答

0

我觉得你可以用两步来解决这个问题。第一步,把最上层的文件夹复制到另一个文件夹里,忽略那些不包含你mp3文件的文件夹。

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

然后,继续按照你在示例代码中处理文件的方式来做。需要注意的是,shutil.copytree这个功能的ignore_patterns选项是从Python 2.5版本开始才有的。

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")

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

一种更符合 Python 风格的方法可能是这样做:

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 方法),然后只有在这个列表不为空时才打开文件。(如果列表不为空,它的值为真)

撰写回答