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:
--- code.py --- file.txt --- my_folder --- my_file.txt
The current folder has two files
file.txt and one folder
my_folder that contains another file
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
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.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
fthat is not a filename (e.g., a folder name), this function would return
Falseand it would be excluded from the iteration.
- You place any filename
fthat 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 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.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.