Python File Search: Find Files in Folder

In Python, you can use the os and os.path modules to find a specific file in a folder. Below is an example code demonstrating how to find a file named example.txt.

import os

# 定义要查找的文件名
file_name = "example.txt"

# 获取当前工作目录
dir_path = os.getcwd()

# 遍历文件夹下的所有文件和子文件夹
for root, dirs, files in os.walk(dir_path):
    for file in files:
        if file == file_name:
            # 找到目标文件
            file_path = os.path.join(root, file)
            print("找到文件:", file_path)

In the example above, we first define the file name we want to find as example.txt, then retrieve the current working directory. Next, we use the os.walk() method to traverse all files and subdirectories in the folder, and then search for the target file in each folder. If the target file is found, we will output the file’s path.

You can modify the file name and folder path as needed to find a specific file.

bannerAds