如何使用Python查找文件?
要在目录中使用Python查找文件,可以使用os.walk遍历目录树,然后按如下方式查找文件:
阅读更多:Python 教程
示例
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']
极客教程