如何使用Python查找文件?
要使用python在目录中查找文件,您可以使用目录树os.walk查找文件,如下所示-
示例
import os
def find_file(file_name, directory_name):
files_found = []
for path, subdirs, files in os.walk(directory_name):
for name in files:
if(file_name == name):
file_path = os.path.join(path,name)
files_found.append(file_path)
return files_found
find_file('my_file.txt', 'my_folder')当您运行此脚本并具有以下文件夹结构时-
my_folder/
another_folder/
my_file
another_file
hello.py
my_file输出结果你会得到输出-
['/my_folder/another_folder/my_file', '/my_folder/my_file']
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短