List files ONLY in the current directory
To fetch only files in the current directory, you can run:
This code utilizes list comprehension combined with os.path.isfile()
, returning a neat list of filenames.
Techniques for directory listing: 'os' and 'pathlib'
Clearly os.listdir
is handy, but for increased efficiency use os.scandir()
, particularly for Python 3.5 and newer. os.scandir()
retains a scanning iterator - enhancing performance by bypassing constant system calls.
Now let's modernize with the pathlib
module that offers object-oriented filesystem paths:
While filtering files in pathlib
, we utilize is_file()
, mirroring the function of os.path.isfile()
:
Order in chaos: Arranging files by extension
Categorization is key. Let's classify files based on their extensions using a smart dictionary comprehension:
To move files based on their respective extension, shutil
module steals the show:
And remember, always use exceptions to trap potential errors that may occur due to operations on "ghost" files or hidden "trap" folders:
Keeping it simple
Maybe you want simplicity and do not want to have to import multiple modules:
Recursion control: Handle with care
The powerhouse function os.walk
mimics the behavior of processing only files, but for recursive directory traversal. But with great power, comes great responsibility:
This code curbs recursion by clearing the dirs
list and breaking after the first loop iteration.
Was this article helpful?