- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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 os module with the walk() function. 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']
Advertisements