In this Python tutorial, how to get all files in a directory in Python.
get all files in a directory in Python
Here, we can see how to list all files in a directory in Python.
- In this example, I have imported a module called os and declared a variable as a path, and assigned the path to list the files from the directory.
- An empty variable is declared as list_of_files, and the root is used to print all the directories, and dirs is used to print all the subdirectories from the root, files are used to print all the files from the root and directories.
- The os. walk() is used to generate the filename in the directory tree by walking the tree, the for loop is used for iteration.
- The path.join is used to combine one or more paths into a single path to combine the files os methods like os.walk() to create the final path.
- The list_of_files.append(os.path.join(root,file)) is used to append the generated files to an empty variable, to print the list of files, I have used print(name).
Example:
import os
path =r'C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work'
list_of_files = []
for root, dirs, files in os.walk(path):
for file in files:
list_of_files.append(os.path.join(root,file))
for name in list_of_files:
print(name)
All the files from the directories can be seen in the output. You can refer to the below screenshot for the output.
This is how to get all files from a directory in Python.
I hope you got an idea of how to get all files in a directory in Python.
You may also like:
- Copy File and Rename in Python
- Write String to a .csv File in Python
- Read the file as a string in Python [5 Methods]
- How to rename a file in Python [4 methods]
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.