Python File Search: Find Files by Name
In Python, the os module can be used to search for files with a specific name. Here is a common method:
import os
def find_files(directory, filename):
results = []
for root, dirs, files in os.walk(directory):
if filename in files:
results.append(os.path.join(root, filename))
return results
# 指定要搜索的目录和文件名
directory = "C:/Users/username/Documents"
filename = "example.txt"
# 查找指定名称的文件
found_files = find_files(directory, filename)
# 输出结果
if found_files:
print("找到以下文件:")
for file in found_files:
print(file)
else:
print("未找到指定文件")
The find_files function in the code above takes a directory and a file name as parameters, and uses the os.walk function to traverse all files in the directory and its subdirectories. If a file with the specified name is found, its path is added to the result list. Finally, the corresponding information is output based on the result list.