- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
File Searching using Python
Python can search for file names in a specified path of the OS. This can be done using the module os with the walk() functions. This will take a specific path as input and generate a 3-tuple involving dirpath, dirnames, and filenames.
In the below example we are searching for a file named smpl.htm starting at the root directory named “D:\”. The os.walk() function searches the entire directory and each of its subdirectories to locate this file. As the result we see that the file is present in both the main directory and also in a subdirectory. We are running this program in a windows OS.
Example
import os def find_files(filename, search_path): result = [] # Wlaking top-down from the root for root, dir, files in os.walk(search_path): if filename in files: result.append(os.path.join(root, filename)) return result print(find_files("smpl.htm","D:"))
Output
Running the above code gives us the following result −
['D:TP\smpl.htm', 'D:TP\spyder_pythons\smpl.htm']
- Related Articles
- File Searching using C#
- Matching Versus Searching in Python
- How do Python Dictionary Searching works?
- The netrc file processing using Python
- How to rename a file using Python?
- How to delete a file using Python?
- How to remove a file using Python?
- How to find a file using Python?
- How to extract file extension using Python?
- Reading and Writing CSV File using Python
- How to create a duplicate file of an existing file using Python?
- How to Find Hash of File using Python?
- How to create an empty file using Python?
- How to create a tar file using Python?
- How to create a zip file using Python?

Advertisements