简体   繁体   English

如何递归搜索 Python 中的文件

[英]How can I recursively search for a file in Python

I have a program that asks the user for a path and then searches for a filename entered by the user.我有一个程序询问用户路径,然后搜索用户输入的文件名。

I have already tried os.listdir , but it returns just the files and subdirectories directly inside the path.我已经尝试过os.listdir ,但它只返回路径内的文件和子目录。
It also does not search the subdirectories for the files.它也不搜索文件的子目录。
I also don't know how to use os.walk() method.我也不知道如何使用os.walk()方法。

Any help on how to do that?关于如何做到这一点的任何帮助?

You can use the glob.glob() function to do the job.您可以使用glob.glob() function 来完成这项工作。 Syntax:句法:

glob.glob(path, recursive=True)

Example code:示例代码:

import glob
path = "C:\\Users\\<username>\\Example"
names = glob.glob(path +  + "\\*\\*.*", recursive=True)

This searches recursively in the directory and returns a list of the files found.这会在目录中递归搜索并返回找到的文件列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM