How to List Files in a Directory - Python

Getting a list of files in a directory is pretty easy in python, and gladly there isn’t just one way of doing it. In this tutorial I’ll show you 3 to 4 ways of doing that.


Method 1: using os.listdir() function

  


import os

# Path to the directory you wish to list
path = "."

# get the list of files in path
dir_list = os.listdir(path)

for file in dir_list:
    print(file)

The listdir() function returns a list of files in the specified path.

Filtering specific files

There may be times when you only want to get list of all ".txt", ".py" etc. files in a directory, you can achieve that by using the endswith() function.

  


import os

# Path to the directory you wish to list
path = "."

# get the list of files in path
dir_list = os.listdir(path)

for file in dir_list:
    if(file.endswith(".txt")):
        print(file)

You can see we just made a bit of edition to our code.

Method 2: using os.scandir() function

os.scandir() function returns an iterator of DirEntry objects for a given path.

  


import os

# Path to the directory you wish to list
path = "."

obj = os.scandir(path)

for entry in obj:
    print(entry.name)

Method 3: using os.walk() function

The os.walk() is a directory tree generator, it takes a path argument and then returns a 3-tuple.

  • dirpath - a string, representing a path to the directory.
  • dirnames - a list of names of subdirectories in dirpath.
  • filenames - a list of file names in dirpath.

  


import os

# Path to the directory you wish to list
path = "."

for (dirpath, dirnames, filenames) in os.walk(path):
    print(f"directory path: {dirpath}")
    print(f"subdirectories: {dirnames}")
    print(f"files: {filenames}")

Method 4: using pathlib module

The pathlib is a filesystem module, it has classes that allows you to work with filesystem. The Path is the most very common.
The Path class has bunch of methods that allows you to work with filesystem, such as mkdir(), rmdir(), globe(), rename(). etc, you can read more about the pathlib module from the Python Documentation
In this example we'll only be using the globe() method.

  


from pathlib import Path

# Initialize an object of Path with a directory path
path = Path(".")

for file in path.globe("*"):
    print(file.name)

In the code above we used the globe() function to get a list of specific files, the globe() function takes a pattern as an argument, you can see we used an asterisk "*" which means that we want the list of all files in the directory.
Using the globe() method makes it easy to filter files, for example example you want the list of all files with .py extension, see example below:

  


from pathlib import Path

# Initialize an object of Path with a directory path
path = Path(".")

for file in path.globe("*.py"):
    print(file.name)

In the above example, *.py means all files with .py extension.