How to List All Files ONLY in the Current Directory?

Problem Formulation

How to list all files in the current directory given these constraints:

  • Non-Recursive: You do not want to list files in subdirectories.
  • ONLY Files: You do not want to list folder names.
  • Current Directory: You run the Python script from the current directory.

Here’s an example structure:

current_folder
--- code.py
--- file.txt
--- my_folder
    --- my_file.txt

The current folder has two files code.py and file.txt and one folder my_folder that contains another file my_file.txt.

The code.py file contains your code to list all files in the current directory.

Your desired output for this problem is:

# Output:
['code.py', 'file.txt']

πŸ’‘ Note: This is non-recursive, so you don’t want to obtain the file my_file.txt that is in the subdirectory my_folder.

One-Liner Solution

The most Pythonic way to list ONLY files in the current directory non-recursively and without listing folders is to use the os module‘s functions os.listdir() and os.path.isfile() within a list comprehension statement like so:

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

You can see this in action here:

import os
files = [f for f in os.listdir('.') if os.path.isfile(f)]
print(files)
# ['code.py', 'file.txt']

Let’s decompose this list comprehension statement:

  • You iterate over all files using os.listdir('.'). The result of this function is a list of strings containing file and folder names. In our example, this would evaluate to the list ['code.py', 'file.txt', 'my_folder'].
  • You restrict the iterable using the if os.path.isfile(f) clause to all strings that are filenames. For a string value f that is not a filename (e.g., a folder name), this function would return False and it would be excluded from the iteration.
  • You place any filename f that satisfies these two conditions in a list without modifying it.

The result is a list of string filenames—no folder names and no filenames of files in subdirectories (non-recursive).

If you have trouble understanding list comprehension in Python, feel free to check out my in-depth blog tutorial and watch the following video:

Of course, you can also use a multi-liner without list comprehension like so:

import os


files = []
for f in os.listdir('.'):
    if os.path.isfile(f):
        files.append(f)
        
print(files)
# ['code.py', 'file.txt']

This is semantically identical—only a little less concise.

To find out various alternative ways to list files in a current directory recursively and non-recursively and with and without folders, check out our full tutorial here:

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!