How To List Files With A Certain Extension in Python

How To List Files With A Certain Extension in Python

list all files in a directory:

before going to list a files with certain extension, first list all files in the directory then we can go for the required extension file. In python to list all files in a directory we use os.listdir library. In this we have to mention the path of a directory which you want to list the files in that directory. For this we have to import os.

import os
x = os.listdir(r"C:\Users\enaknar\Desktop\pycharm")
print (x)
for i in x:
  print(i)

Output:

[ '1-1.py', '1-2.py', '1-3.py', 'asf', 'asf.txt', 'fsg.py', 'read-1.py']

1-1.py
1-2.py
1-3.py
asf
asf.txt
fsg.py
read-1.py

Here we are storing all the files of a directory "C:\Users\enaknar\Desktop\pycharm" in variable x as a list.

we are printing the list x and we are printing list one by one using for loop. in this way we can print or list all files in a particular directory.

List Files With A Certain Extension in Python

in the previous example we have seen how to list all files in a directory, now in this example i will show you how to print or list the files with certain extension.

#find a file ends with .txt
import os
x = os.listdir(r"C:\Users\devops\Desktop\pycharm")
for i in x:
 if i.endswith(".txt"):
  print(i)

to check a file with certain extension in python we use endswith method. The endswith() method returns True if a string ends with the specified suffix. If not, it returns False.

Output:

asf.txt

Process finished with exit code 0

so here writing one more if loop like if it is finds a file with extension with ".txt" it will print the file.

in this way we can print or list files with a certain extension in python.

  • List Files With A Certain Extension in Python
  • list all files in a directory in python
  • python list files in a directory
  • list files in a directory python

Leave a Reply

Your email address will not be published. Required fields are marked *