深度阅读

How to find a file by name in Python

作者
作者
2023年08月22日
更新时间
9.9 分钟
阅读时间
0
阅读量

To find a file by name in Python, you can use the os.walk() function which generates the file names in a directory tree, and then filter the results based on the filename. Here is an example code snippet to find a file named “example.txt” in a directory and its subdirectories:

import os

def find_file(filename, search_path):
    for root, dir, files in os.walk(search_path):
        if filename in files:
            return os.path.join(root, filename)

Then you can call the find_file() function and pass in the filename and the directory path to search in:

filename = 'example.txt'
search_path = '/Users/username/Documents'
file_path = find_file(filename, search_path)
print(file_path)

This will return the path of the first occurrence of the file with the given filename in the directory and its subdirectories. If the file is not found, the function will return None.
Note that the search may take a while if you are searching in a large directory tree.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。