检查指定目录中是否存在任何 mp3 文件
checking if any mp3 files exist in a specified directory
我想使用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))]
只需将附加条件 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"]
试试这个:
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"]
我个人更喜欢 pathlib
模块,所以我将 post 使用它来回答。请记住,这不是一种递归方法,因此它只会向下一级搜索您想要的 .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
个文件。
我想使用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))]
只需将附加条件 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"]
试试这个:
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"]
我个人更喜欢 pathlib
模块,所以我将 post 使用它来回答。请记住,这不是一种递归方法,因此它只会向下一级搜索您想要的 .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
个文件。