Planet Python

Real Python: How to Get a List of All Files in a Directory With Python

The pathlib module in Python provides methods to list directory contents, including .iterdir(), .glob(), and .rglob(). The .iterdir() method returns a generator that yields Path objects representing child items in a directory. The .glob() and .rglob() methods support glob patterns for filtering files with specific extensions or names. By combining these methods with comprehensions or filter functions, you can perform advanced filtering. The pathlib module is a more efficient and convenient way to work with file paths compared to the os module, which handles paths as strings. Working with paths as strings can be tricky, especially when dealing with multiple operating systems. The pathlib module takes care of the tricky stuff, allowing you to focus on the main logic of your code. To use the pathlib module, you need to create a Path object, which is OS-aware and provides various methods and properties. The .iterdir() method can be used to get a list of all files and folders in a directory, while .glob() and .rglob() can be used to find files with specific extensions or names. The choice of method depends on the specific use case, and you can explore different techniques in the pathlib module for listing directory contents.
favicon
realpython.com
realpython.com