【问题标题】:checking if any mp3 files exist in a specified directory检查指定目录中是否存在任何 mp3 文件
【发布时间】:2021-09-08 23:46:34
【问题描述】:

我想使用python来检查指定目录中是否存在任何mp3文件。如果确实存在,我想将文件路径存储在变量中。

这是一些我必须检查是否存在任何文件的代码。如何修改?

import os
dir = os.path.dirname(__file__) or '.'
dir_path = os.path.join(dir, '../folder/')
onlyfiles = [f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f))]

【问题讨论】:

  • “我如何修改它”不是一个有用的问题。你想完成什么,你尝试了什么,它是如何不起作用的?第一部分答对了,现在回答第二和第三部分!
  • 这能回答你的问题吗? Find a file in python

标签: python directory path operating-system


【解决方案1】:

只需将附加条件 f[-4:]==".mp3" 添加到列表解析中的 if 语句,使其现在变为:

onlyfiles = [f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f)) and f[-4:]==".mp3"]

【讨论】:

    【解决方案2】:

    试试这个:

    import os
    
    dir = os.path.dirname("/path/to/your/dir/"); dir_path = dir;
    onlyfiles = [f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f)) and f[-4:]==".mp3"]
    

    【讨论】:

      【解决方案3】:

      我个人更喜欢pathlib 模块,因此我将使用它发布答案。请记住,这不是一种递归方法,因此它只会向下一层搜索您想要的 .mp3 文件:

      import pathlib as path
      
      dirname = path.Path(input("Enter the path to the directory to search: ")).glob("*.mp3")
      paths = []
      
      for file in dirname:
          paths.append(str(file))
      

      我将路径存储在一个列表中,以防万一文件夹中有更多 .mp3 文件。

      【讨论】:

        猜你喜欢
        • 2017-12-16
        • 1970-01-01
        • 2016-02-01
        • 2012-03-19
        • 2011-04-29
        • 2018-10-01
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        相关资源
        最近更新 更多