- Find Files Using Python
- Find File With the os.walk() Function in Python
- Find File With the glob.glob() Function in Python
- Find File With the Path.glob() Function in Python
- Related Article — Python File
- How to Find all files in a Directory with specific extension in Python
- Python program to find all the .txt files from a directory
- Python program to find all the Python .py files from a directory
- Python program to find all the Images .jpeg, .jpg, .png files from a directory
- Conclusion
- Find Files Using Python
- Find File With the os.walk() Function in Python
- Find File With the glob.glob() Function in Python
- Find File With the Path.glob() Function in Python
- Related Article — Python File
Find Files Using Python
- Find File With the os.walk() Function in Python
- Find File With the glob.glob() Function in Python
- Find File With the Path.glob() Function in Python
This tutorial will discuss the methods to find a file in Python.
Find File With the os.walk() Function in Python
If we want to find the path of a specific file on our machine with python, we can use the os module. The os module provides many os-related functionalities to our code. The os.walk() function takes a path string as an input parameter and gives us the directory path, the directory name, and the filename for each file in the path . The sample code below shows us how to find a file in Python with the os.walk() function.
import os def findfile(name, path): for dirpath, dirname, filename in os.walk(path): if name in filename: return os.path.join(dirpath, name) filepath = findfile("file2.txt", "/") print(filepath)
/Users\maisa\Documents\PythonProjects\file2.txt
In the above code, we declared the findfile() function that uses os.walk() function to find our file. The findfile() function takes the file’s name and the root path as input parameters and returns the path of our specified file. This approach gives us the absolute path of the file.
Find File With the glob.glob() Function in Python
We can also use the glob.glob() function to solve our current problem. The glob.glob() function takes a pathname as an input parameter and returns a list of all the file paths that match the input argument. We can specify a regular expression as an input parameter that matches our file only. The sample code below shows us how to find a file in Python with the glob.glob() function.
import glob filepath = glob.glob('**/file.txt', recursive=True) print(filepath)
We passed our file name as the input parameter to the glob.glob() function, and it returned the relative path of our file. This method can give us the relative path as well as the absolute path of our file.
Find File With the Path.glob() Function in Python
Another approach is to use the pathlib module. This Python module offers classes that represent filesystem paths for different operating systems. We can use the Path.glob() function inside the pathlib module to solve our specific problem. This function is similar to the glob() function inside the glob module. The Path.glob() function takes a pattern as an input parameter and returns a list of path objects that match the input argument. The sample code snippet shows us how to find a file in Python with the pathlib module.
import pathlib filepath = sorted(pathlib.Path('.').glob('**/file2.txt')) print(filepath)
We passed a pattern string that matches our file to the Path.glob() function. The Path.glob() function returns us a list of WindowsPath objects that match the pattern. With this method, we get path objects specific to our operating system.
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
Related Article — Python File
How to Find all files in a Directory with specific extension in Python
Python comes with a standard module called os that is used to handle file management using Python. With the help of Python os modules, we can perform many file management tasks like creating, renaming, moving, copying, searching, and deleting files and directories. If you want to know more about Python file management with the os module then click here .
In this tutorial, we will not be covering all the important methods of the os module. Instead, we will be using it to find specific extension files from a directory. For example, we will be writing a python script that can find all the .txt, .doc, .py, .jgeg, etc., files from a specific directory.
Python program to find all the .txt files from a directory
We will start with finding all the .txt files present in a specific directory. For this tutorial, I will be searching all the .txt files present in the same directory where my Python script is located and printing the complete path as an output.
import os for file in os.listdir(): if file.endswith(".txt"): print(os.path.join(os.getcwd(),file))
C:\Users\tsmehra\Desktop\code\data.txt C:\Users\tsmehra\Desktop\code\external_css.txt C:\Users\tsmehra\Desktop\code\external_script.txt C:\Users\tsmehra\Desktop\code\passwords_list.txt C:\Users\tsmehra\Desktop\code\vulnarable_banners.txt
The os.listdir() function will return a list of all the files and directories present in the current directory. The .endswith() is a Python string function that will check if a file ends with an extension of .txt . The os.getcwd() function returns the absolute path of the current working directory. The os.path.join() method will join the current working directory path with the file name. In the above example, I have listed all the .txt files that are present in the same directory where the Python script is located. If you want to find files of different directories there you need to change the working directory by using the os.chdir() method.
import os directory = r'C:\Users\tsmehra\Documents' os.chdir(directory) #change the current working directory for file in os.listdir(): if file.endswith(".txt"): print(os.path.join(os.getcwd(),file))
C:\Users\tsmehra\Documents\allnew.txt C:\Users\tsmehra\Documents\config.txt C:\Users\tsmehra\Documents\Python has many built.txt
It’s very important to use the r»» prefix before the directory name else we need to specify the escape characters.
Python program to find all the Python .py files from a directory
The program will remain the same. The only change we need to make in order to retrieve all the .py files is in the endswith() method.
import os #directory = r'' #os.chdir(directory) #change the current working directory for file in os.listdir(): if file.endswith(".py"): #only python .py files print(os.path.join(os.getcwd(),file))
C:\Users\tsmehra\Desktop\code\assambaly.py C:\Users\tsmehra\Desktop\code\attack.py C:\Users\tsmehra\Desktop\code\checkweather.py C:\Users\tsmehra\Desktop\code\client.py C:\Users\tsmehra\Desktop\code\colorful.py C:\Users\tsmehra\Desktop\code\compareimage.py C:\Users\tsmehra\Desktop\code\contours.py C:\Users\tsmehra\Desktop\code\crackpassword.py C:\Users\tsmehra\Desktop\code\CssJSlinks.py C:\Users\tsmehra\Desktop\code\dDosattqack.py C:\Users\tsmehra\Desktop\code\deconde.py C:\Users\tsmehra\Desktop\code\DecryptFile.py .
Python program to find all the Images .jpeg, .jpg, .png files from a directory
Now let’s find all the images present in a specific directory. The code will remain pretty the same as we have written for the above examples, but here will be making some changes in the conditional if statement.
import os directory = r'C:\Users\tsmehra\Pictures' os.chdir(directory) #change the current working directory to pictures for file in os.listdir(): if file.split(".")[-1].lower() in ["apng", "avif", "gif","jpeg", "jpg", "png", "svg"]: print(os.path.join(os.getcwd(),file))
C:\Users\tsmehra\Pictures\Armstrong_Number_Python.jpg C:\Users\tsmehra\Pictures\Arrays-data-structure.png C:\Users\tsmehra\Pictures\arrays.png C:\Users\tsmehra\Pictures\atom.png C:\Users\tsmehra\Pictures\best python libraries 2021.jpg C:\Users\tsmehra\Pictures\blur faces with open cv.jpg C:\Users\tsmehra\Pictures\choosepython.jpg C:\Users\tsmehra\Pictures\contours image opencv python.jpg C:\Users\tsmehra\Pictures\contours on the blank image.jpg C:\Users\tsmehra\Pictures\coolpad python online copiler.jpg
Conclusion
Let’s sum up the above Python tutorial. In this tutorial, you learned how to find specific file extensions in Python. The module we used in our tutorial is os which is a Python standard module for file and directory management. If you are searching for the files that are present in the same directory of your Python script, then you do not need to change the working directory, but if you wish to find files from another directory there, you need to change the working directory using the os.chdir() method. The os.listdir() will list out all the directories and files present in the current working directory, and using the if statement and endswith() statement we can find the specific extension files.
People are also reading:
Find Files Using Python
- Find File With the os.walk() Function in Python
- Find File With the glob.glob() Function in Python
- Find File With the Path.glob() Function in Python
This tutorial will discuss the methods to find a file in Python.
Find File With the os.walk() Function in Python
If we want to find the path of a specific file on our machine with python, we can use the os module. The os module provides many os-related functionalities to our code. The os.walk() function takes a path string as an input parameter and gives us the directory path, the directory name, and the filename for each file in the path . The sample code below shows us how to find a file in Python with the os.walk() function.
import os def findfile(name, path): for dirpath, dirname, filename in os.walk(path): if name in filename: return os.path.join(dirpath, name) filepath = findfile("file2.txt", "/") print(filepath)
/Users\maisa\Documents\PythonProjects\file2.txt
In the above code, we declared the findfile() function that uses os.walk() function to find our file. The findfile() function takes the file’s name and the root path as input parameters and returns the path of our specified file. This approach gives us the absolute path of the file.
Find File With the glob.glob() Function in Python
We can also use the glob.glob() function to solve our current problem. The glob.glob() function takes a pathname as an input parameter and returns a list of all the file paths that match the input argument. We can specify a regular expression as an input parameter that matches our file only. The sample code below shows us how to find a file in Python with the glob.glob() function.
import glob filepath = glob.glob('**/file.txt', recursive=True) print(filepath)
We passed our file name as the input parameter to the glob.glob() function, and it returned the relative path of our file. This method can give us the relative path as well as the absolute path of our file.
Find File With the Path.glob() Function in Python
Another approach is to use the pathlib module. This Python module offers classes that represent filesystem paths for different operating systems. We can use the Path.glob() function inside the pathlib module to solve our specific problem. This function is similar to the glob() function inside the glob module. The Path.glob() function takes a pattern as an input parameter and returns a list of path objects that match the input argument. The sample code snippet shows us how to find a file in Python with the pathlib module.
import pathlib filepath = sorted(pathlib.Path('.').glob('**/file2.txt')) print(filepath)
We passed a pattern string that matches our file to the Path.glob() function. The Path.glob() function returns us a list of WindowsPath objects that match the pattern. With this method, we get path objects specific to our operating system.
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.