Open In App

File Searching using Python

Last Updated : 29 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

There may be many instances when you want to search a system.Suppose while writing an mp3 player you may want to have all the ‘.mp3’ files present. Well here’s how to do it in a simple way. 
This code searches all the folders in the file it’s being run. If you want some other kinds of files just change the extension.
 

Python3




# Python code to search .mp3 files in current
# folder (We can change file type/name and path
# according to the requirements.
import os
 
# This is to get the directory that the program
# is currently running in.
dir_path = os.path.dirname(os.path.realpath(__file__))
 
for root, dirs, files in os.walk(dir_path):
    for file in files:
 
        # change the extension from '.mp3' to
        # the one of your choice.
        if file.endswith('.mp3'):
            print (root+'/'+str(file))


os is not an external library in python. So I feel this is the simplest and the best way to do this.

Use the glob module:

One alternative approach to searching for files with a specific extension is to use the glob module. This module provides a way to search for files with a specific pattern using the glob function.

For example, to search for all .txt files in the current directory, you could use the following code:

Python3




import glob
 
files = glob.glob('*.mp3')
for file in files:
    print(file)


The glob function returns a list of file paths that match the specified pattern. In this case, the pattern ‘*.mp3’ matches all files in the current directory that have the .mp3 extension.

You can also specify a different directory to search in by including the path in the pattern. For example, ‘path/to/directory/*.mp3’ would search for all .mp3 files in the path/to/directory directory.

The glob module also supports more advanced patterns, such as ‘*.mp3’ to match all files with the .mp3 extension in any directory, or ‘**/*.mp3’ to match all .mp3 files in all subdirectories, recursively. You can learn more about the different pattern options in the documentation for the glob module.

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads