📜  使用Python进行文件搜索

📅  最后修改于: 2022-05-13 01:55:39.055000             🧑  作者: Mango

使用Python进行文件搜索

当您想要搜索系统时,可能会有很多情况。假设在编写 mp3 播放器时,您可能希望所有的“.mp3”文件都存在。那么这里是如何以一种简单的方式做到这一点。
此代码搜索正在运行的文件中的所有文件夹。如果您想要一些其他类型的文件,只需更改扩展名。

Python3
# Python code to search .mp3 files in current
# folder (We can change file type/name and path
# according to the requirements.
import os
 
# This is to get the directory that the program
# is currently running in.
dir_path = os.path.dirname(os.path.realpath(__file__))
 
for root, dirs, files in os.walk(dir_path):
    for file in files:
 
        # change the extension from '.mp3' to
        # the one of your choice.
        if file.endswith('.mp3'):
            print (root+'/'+str(file))