649
In this example we will find all files with a certain extension in a directory using python
We have 2 examples on how to do this.
Example 1
We use a for loop, you can search for files with .py extension using glob().
The * denotes all files with the given extension.
import glob, os # folder to check os.chdir("numpy") # find all .py files and display for file in glob.glob("*.py"): print(file)
When you run this you will see something like this depending on the folder and contents
>>> %Run findfileext1.py numparrayarithmetic1.py numparrayarithmetic2.py numprandomrand.py numpyarraycopy1.py numpyarraycopy2.py numpyarraycopy3.py numpyarraylargest1.py numpyarraylargest2.py numpyhistrandom.py numpylogical.py numpylogicalnot.py numpylogicalor.py numpylogicalxor.py
Example 2
In this example we use the endswith() method to check for the .py extension.
We use a for loop and iterate through each file of the directory called numpy
import os # folder to check for file in os.listdir("numpy"): if file.endswith(".py"): #python file extension print(file) #display files
Again, same as example 1 result
>>> %Run findfileext2.py numparrayarithmetic1.py numparrayarithmetic2.py numprandomrand.py numpyarraycopy1.py numpyarraycopy2.py numpyarraycopy3.py numpyarraylargest1.py numpyarraylargest2.py numpyhistrandom.py numpylogical.py numpylogicalnot.py numpylogicalor.py numpylogicalxor.py