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,
- listdir – Get a List of all Files and folder from the given directory or path
- 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
- glob – Get a List of all files(of specific types) in the current directory
- walk – Get a List of all files from a particular directory
Below is how sample folder looks like,
listdir – Get a List of all Files and folder from the given directory or path
list= os.listdir('C:\Test\gcp') print(list)
Result :
[‘cloud’, ‘DemoAPI’, ‘Test.txt’]
glob – Get a list of all types of files in the current directory
list = glob.glob(".")
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)
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.