How to get all files in a directory in Python?

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.

get all files in a directory in Python
get all files in directory in Python

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: