Explain Codes LogoExplain Codes Logo

List files ONLY in the current directory

python
file-system
pathlib
directory-listing
Alex KataevbyAlex Kataev·Feb 28, 2025
TLDR

To fetch only files in the current directory, you can run:

import os print([f for f in os.listdir('.') if os.path.isfile(f)])

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:

from pathlib import Path # Directory listing with pathlib, includes free "wow" factor files_in_current_directory = (entry for entry in Path('.').iterdir() if entry.is_file()) print(list(files_in_current_directory))

While filtering files in pathlib, we utilize is_file(), mirroring the function of os.path.isfile():

# Customary 'filter out the junk' Jenga move files_in_current_directory = filter(lambda p: p.is_file(), Path('.').iterdir()) print(list(files_in_current_directory))

Order in chaos: Arranging files by extension

Categorization is key. Let's classify files based on their extensions using a smart dictionary comprehension:

# Sorting files like a librarian, but without the glasses files_by_extension = { ext: [file for file in os.listdir('.') if file.endswith(ext)] for ext in ['.jpg', '.txt', '.py', '.md'] # Add extensions as needed }

To move files based on their respective extension, shutil module steals the show:

import shutil # Moving files like a chess grandmaster for ext, files in files_by_extension.items(): for file in files: shutil.move(file, f"destination_folder/{file}")

And remember, always use exceptions to trap potential errors that may occur due to operations on "ghost" files or hidden "trap" folders:

try: # A ticking time bomb of a file operation except OSError as e: print(f"Error: {e.strerror}")

Keeping it simple

Maybe you want simplicity and do not want to have to import multiple modules:

from glob import glob print(glob('*.py')) # Lists all Python files in the current directory; doesn't make coffee, sorry

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:

for root, dirs, files in os.walk('.', topdown=True): # 'dirs.clear()' acts like a door bouncer for directories dirs.clear() print(files) break # Stops the iteration - not your Python script!

This code curbs recursion by clearing the dirs list and breaking after the first loop iteration.