Signup/Sign In
PUBLISHED ON: FEBRUARY 2, 2021

List all files in directory in Python

In this article, we will learn how to list all files in the given directory in Python. We will use some built-in functions, different modules available in Python to search and list all files in the specified directory or current directory. Let's first have a quick look over the introduction to the directory and what modules we will study to list all files in Python.

Directory in Python

A directory is similar to a folder where unit organizational structuring occurs for storing and locating files. Python supports a number of APIs and modules to list the directory contents. We will look at the following modules to list all the files in the directory.

  1. os module
  2. glob module

List all files using the os module

Under the os module, we can use several methods to get a list of files of a directory in Python.

  • os.listdir()
  • os.walk()
  • os.scandir()
  • os.path.isfile()

Example: List all files using the os.listdir() Method

This method returns the list of all files present in a specified directory. Linux users can get the list of files by using the standard ls command on the Linux terminal.

import os

# pass the path of the directory
path = 'C:/Users/Yukti/Desktop/test'

files = os.listdir(path)
print(files)


['filename.txt', 'oldpas.class', 'oldpas.java']

Example: List all files using os.walk() Method

This method is used to list all files in a recursive manner. It lists file names in a directory tree. Using os.walk(), the user traverses each subdirectory within a directory and extracts the files in a top-down manner.

# import module
import os

#pass the path of the directory
path = "C:/Users/Yukti/Desktop/test"

#to store files in a list
list = []

#dirs = directories
for (root, dirs, file) in os.walk(path):
    for f in file:
        print(f)


filename.txt
oldpas.class
oldpas.java

Example: List all files using os.scandir() Method

This method is supported in Python 3 and above. Please check your version before using this method. This method scans the directory and returns an iterator of os.DirEntry objects corresponding to entries in it.

# import module
import os

#path of the directory
path="C:/Users/Yukti/Desktop/test"

object = os.scandir(path)

for x in object:
     if(x.is_dir() or x.is_file()):
            print(x.name)


filename.txt
oldpas.class
oldpas.java

Example: List only files in the current directory using os.path.isfile() Method

This method extracts only the files using the path.isfile() inside the os library. This method uses a list comprehension to filter out only files.

# Import module
import os

path = '.'

#List only files
files = [f for f in os.listdir(path) if os.path.isfile(f)]

#loop to print each filename separately
for x in files:
    print(x)


assignment.docx
color.docx
data.yml
models.xml
New DOCX Document.docx
Picture1.png
python.py
............

Note: It does not work for other directories as the variable 'f' is not an absolute path, but a relative path to the current directory.

List all files using glob module

Under glob module we will learn:

  • glob.glob()
  • glob.iglob()

Example: List all files using glob.glob() Method

This module retrieves files/path names by matching them to the specified pattern. glob is mostly a filename pattern matching library, but it is also used to list items in the current directory. glob() provides some wild card operators such as "*", "?", [ranges] to make path retrieval more simple and convenient. The wildcard character '*' is used to match all the items in the current directory.

import glob

# Using '*' pattern
files = glob.glob('test/*.*')
print('\nUsing *: ',files)

files = glob.glob('test/*[0-9]*')
print('Using ranges: ',files)


Using *: ['test\\filename.txt', 'test\\oldpas.class', 'test\\oldpas.java', 'test\\term1.txt']
Using ranges: ['test\\88yukt', 'test\\term1.txt']

Example: List all files using glob.iglob() Method

This method prints the list of the filenames from the specified directory.

glob.iglob(path, *, recursive=False)

import glob
 
# Using '*' pattern
files = glob.iglob('test/*.*',recursive=True)
for x in range(4):
    print(next(files))


test\filename.txt
test\oldpas.class
test\oldpas.java
test\term1.txt

Conclusion

In this article, we learned multiple ways and the most convenient methods of listing all files in the directory in Python. We learned different methods from os and glob module to list all files in a directory.



About the author:
An enthusiastic fresher, a patient person who loves to work in diverse fields. I am a creative person and always present the work with utmost perfection.