python - 忽略具有某些文件类型的文件夹

标签 python powershell

我徒劳地尝试重写我在此处找到的旧 Powershell 脚本 - "$_.extension -eq" not working as intended? - 对于Python。我没有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 用户来说是亵渎的,但我们将不胜感激任何帮助。

最佳答案

如果我理解正确,您的核心问题是该脚本正在创建大量空的 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 如果您'对此感到更舒服),然后仅当结果列表非空时才打开文件。 (如果列表非空则为真)

关于python - 忽略具有某些文件类型的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4574716/

相关文章:

powershell - 使用Powershell在断开连接的网卡上设置静态IP,是否可以?

regex - Powershell:如果命令输出与预期的3个字符串数组不同,则发送电子邮件

powershell - 如何检查asp.net mvc 3是否已安装?

python - 为 BigQuery Python CLI 设置 GOOGLE_APPLICATION_CREDENTIALS

python - 将多个数字写入 .pdf 时出错

python - 如何更新 SqlAlchemy 中的所有对象列?

xml - 在PowerShell中按属性对XML元素进行分组的简单方法

powershell - 如何解决 Get-NetConnectionProfile : Provider load failure on x86 Powershell?

python - 在 X 行后的空白行处分割文件

python - 如何还原由openface.AlignDlib.align完成的转换?