Python – Find the list of all Files in the Directory

Today in this article, we shall see how to get python – Find the list of all files in the directory.

We shall see few very simple approaches like using,

  • listdir
  • glob
  • walk

Today in this article, we will cover below aspects,

Below is how sample folder looks like,

Python Find the list of all Files in the Directory

listdir – Get a List of all Files and folder from the given directory or path

list= os.listdir('C:\Test\gcp')
print(list)

Result :

python listdir Get a List of all Files and folder from the given directory or path

[‘cloud’, ‘DemoAPI’, ‘Test.txt’]

glob – Get a list of all types of files in the current directory

list = glob.glob(".")

python glob Get a list of all types of files in the current directory

glob – Get a list of all types of files in the given directory

list = glob.glob('C:\Test\gcp')

glob – Get a List of all files(of specific types) in the current directory

Below logic get a list of all files with extension type as .txt.

list = glob.glob(".txt") 

walk – Get a List of all files from a particular directory

Using walk also a simple interface to achieve the same,

for files in os.walk('C:\Test\gcp'):
 for file in files:
  if file.endswith('.txt'):
   print(file)
Python walk Get a List of all files from a particular directory

Similarly get root or directory list using below,

for root, dirs, files in os.walk('C:\Test\gcp'):
 for dir in dirs:
  print(dir)

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

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