【问题标题】:Check if mp3 file is in given directory检查 mp3 文件是否在给定目录中
【发布时间】:2017-12-16 22:14:53
【问题描述】:

我在这里看不到我做错了什么

import os

def check():
    path = "d://Mu$ic//"
    for file in os.listdir(path):
        if file.endswith("*.mp3"):
            print (os.path.join(path,file))

check()

输出不显示,知道我做错了什么吗?

【问题讨论】:

  • 试试file.endswith('.mp3')
  • 是的,这就是我需要的,谢谢!

标签: python operating-system mp3 listdir


【解决方案1】:

省略* 应该可以,因为endswith 匹配字符串后缀(而不是*.mp3,它是一个通配符):

file.endswith(".mp3"):

另外,您可以将 // 替换为 /

【讨论】:

    【解决方案2】:

    文件夹中只有mp3文件吗?如果是这样,为什么需要检查 endwith?如果 mp3 是该文件夹中唯一的文件类型,它应该能够在不检查它们是否以 .mp3 结尾的情况下返回它们。除非您在那里有其他文件类型,否则您将需要 endwith 检查。我在这里没有结束你的代码,它返回了文件夹中的每个 .wav 文件。

    【讨论】:

      【解决方案3】:

      如果你使用python 3,你也可以使用glob

      import glob
      
      _path = '{0}**/*.mp3'.format("d://Mu$ic//")
      file_lst = glob.glob(_path, recursive=True)
      print(file_lst)
      
      ['2.mp3', '3.mp3', ...]
      

      【讨论】:

        猜你喜欢
        • 2021-09-08
        • 2019-08-28
        • 2016-02-01
        • 2012-03-19
        • 1970-01-01
        • 2010-12-13
        • 1970-01-01
        • 2010-11-04
        • 2019-02-24
        相关资源
        最近更新 更多