How do I list all files of a directory?
In Python, you can use the os module to list all files in 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:
List all files in the current directory using os.listdir() in Python
import os
files = os.listdir()
for file in files:
print(file)
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
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:
List all files in a specific directory using os.listdir(path) in Python
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:
Filter files by extension using list comprehension in Python
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.
Get an iterator yielding os.DirEntry object in Python
import os
path = '/path/to/directory'
for file in os.scandir(path):
if file.is_file():
print(file.name)