How do I list all files of a directory?
In Python, you can use the os
module to list all files in a directory. The os.listdir()
function returns a list of all files and directories in the specified directory.
Here's an example of how to use os.listdir()
to list all files in the current directory:
Watch a video course
Python - The Practical Guide
If you want to list the files in a specific directory, you can pass the directory path as an argument to the os.listdir()
function:
import os
path = '/path/to/directory'
files = os.listdir(path)
for file in files:
print(file)
You can also filter the files by their extension or other attributes using the python built-in functions such as filter, list comprehension and so on.
For example, you can use list comprehension to filter out only .txt files:
import os
path = '/path/to/directory'
txt_files = [file for file in os.listdir(path) if file.endswith('.txt')]
for file in txt_files:
print(file)
You could also use os.scandir() to get a iterator yielding os.DirEntry object that may have more information as well.
import os
path = '/path/to/directory'
for file in os.scandir(path):
if file.is_file():
print(file.name)