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
<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
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
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