Python List Files In Current Directory

5 min read

Listing files in a directory is one of the most fundamental tasks in Python scripting and automation. Still, whether you are building a data processing pipeline, organizing a messy downloads folder, or writing a utility to clean up log files, the ability to programmatically inspect the contents of a folder is essential. That said, python offers several solid ways to achieve this, ranging from the classic os module to the modern, object-oriented pathlib library. Understanding the nuances of each approach allows you to write cleaner, more efficient, and more portable code.

The Modern Standard: Using pathlib

Introduced in Python 3.4, the pathlib module represents filesystem paths as proper objects rather than simple strings. Now, this object-oriented approach makes code more readable and reduces the likelihood of errors related to path separators across different operating systems. For most modern Python applications, this is the recommended starting point Still holds up..

Real talk — this step gets skipped all the time.

To list files in the current working directory using pathlib, you instantiate a Path object representing the current directory (denoted by .) and then iterate over it That's the part that actually makes a difference..

from pathlib import Path

# Get the current directory
current_dir = Path('.')

# Iterate over all entries (files and folders)
for entry in current_dir.iterdir():
    print(entry.name)

The iterdir() method yields Path objects for every item in the directory. is_dir(), .suffix, and .Because these are objects, you immediately gain access to powerful properties like .In real terms, is_file(), . stat() without needing additional imports or string manipulation.

Filtering for Files Only

Often, you only want files, not subdirectories. pathlib makes this filtering intuitive:

from pathlib import Path

current_dir = Path('.')
files_only = [entry for entry in current_dir.iterdir() if entry.

for file in files_only:
    print(file.name)

This list comprehension is highly readable. It creates a list of Path objects representing only files, which you can then pass to other functions for processing, moving, or reading.

Recursive Listing with rglob and glob

One of pathlib's standout features is its powerful pattern matching. If you need to list files recursively (including subdirectories), rglob (recursive glob) is the tool of choice Simple, but easy to overlook..

from pathlib import Path

# Find all .txt files recursively
txt_files = Path('.').rglob('*.txt')

for file in txt_files:
    print(file)

The glob(pattern) method works similarly but only searches the immediate directory. These methods return generators, meaning they are memory efficient even when scanning massive directory trees.

The Classic Approach: The os Module

Before pathlib, the os module was the standard way to interact with the filesystem. And it remains widely used in legacy codebases and is perfectly functional for simple scripts. It treats paths as strings, which requires a bit more manual handling but offers a very direct mapping to underlying system calls Simple, but easy to overlook..

You'll probably want to bookmark this section That's the part that actually makes a difference..

Using os.listdir()

The most basic function is os.listdir(). It returns a list of strings containing the names of the entries in the directory.

import os

# List all entries in current directory
entries = os.listdir('.')

for entry in entries:
    print(entry)

Important Caveat: os.listdir() returns only the base names (strings), not full paths. If you need to check if an entry is a file or get its size, you must manually join the directory path with the entry name using os.path.join().

Filtering Files with os.path

To replicate the "files only" logic using os, the code looks like this:

import os

current_dir = '.'
entries = os.listdir(current_dir)

files_only = []
for entry in entries:
    full_path = os.path.So join(current_dir, entry)
    if os. path.isfile(full_path):
        files_only.

print(files_only)

While verbose, this pattern is extremely common in older Python tutorials and scripts. It works reliably across all Python versions Not complicated — just consistent..

Using os.scandir() for Performance

Introduced in Python 3.scandir()is a significant performance optimization overlistdir(). 5, os.DirEntryobjects. Instead of returning bare strings, it returns an iterator ofos.These objects cache the file type and stat information, avoiding expensive system calls when you check is_file() or is_dir() Simple, but easy to overlook..

import os

with os.') as entries:
    for entry in entries:
        if entry.In practice, scandir('. is_file():
            print(entry.

Using the `with` statement ensures the iterator is properly closed, releasing file descriptors. For scripts scanning directories with thousands of entries, `os.scandir()` is noticeably faster than `os.listdir()` combined with `os.Day to day, path. isfile()`.

## The Glob Module: Pattern Matching Made Simple

If your primary goal is finding files matching a specific pattern (like all CSV files or all images), the `glob` module is often the most concise tool. It returns a list of path strings matching a Unix shell-style wildcard pattern.

```python
import glob

# List all .py files in current directory
python_files = glob.glob('*.py')
print(python_files)

# Recursive search (requires Python 3.5+)
all_python_files = glob.glob('**/*.py', recursive=True)
print(all_python_files)

The glob module is excellent for "find me all X files" tasks. That said, it returns strings, not objects, so you lose the convenient methods found in pathlib. So naturally, it also loads all results into memory at once (a list), whereas pathlib. rglob and os.scandir use iterators/generators And that's really what it comes down to..

Getting File Metadata: Size, Modification Time, and Permissions

Listing filenames is rarely the end goal. That's why usually, you need metadata. Here is how the three main approaches handle retrieving file size and last modification time.

With pathlib (Recommended)

from pathlib import Path
import time

for entry in Path('.Think about it: ctime(stat. On top of that, is_file():
        stat = entry. But iterdir():
    if entry. ').st_size / 1024
        mod_time = time.That said, stat()
        size_kb = stat. st_mtime)
        print(f"{entry.name:30} | {size_kb:>8.

The `.stat()` method returns an `os.stat_result` object containing `st_size`, `st_mtime` (modification time), `st_ctime` (creation/metadata change time), and permission bits.

### With `os.scandir()` (High Performance)

Because `os.DirEntry` caches the stat result, accessing `.stat()` on an entry from `scandir` is often free (no extra syscall) on Windows and very cheap on Unix.

```python
import os
import time

with os.is_file():
            info = entry.stat()
            print(f"{entry.Consider this: scandir('. On the flip side, st_size} bytes - {time. ') as entries:
    for entry in entries:
        if entry.Which means name} - {info. ctime(info.

## Handling Hidden Files and Special Entries

On Unix-like systems (Linux, macOS), files starting with a dot (`.`) are considered hidden. On Windows, files have a "Hidden" attribute. Here's the thing — by default, `os. listdir()`, `pathlib.Plus, path. iterdir()`, and `glob.glob('*')` **do not** hide these files; they return everything except the special `.` (current) and `..` (parent) entries.

If you need to filter out hidden files cross-platform, you need a helper function:

```python
import os
from pathlib import Path

def is_hidden(filepath):
    name = os.path.basename(os.path.abspath(filepath))
    if name.startswith('.'):
Newest Stuff

Fresh Reads

Others Liked

Still Curious?

Thank you for reading about Python List Files In Current Directory. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home