Python – List Files in a Directory

22 Jun, 2022
In this article, we will cover how do we list all files in a directory in python.
A Directory also sometimes known as a folder is a unit organizational structure in a computer’s file system for storing and locating files or more folders. Python now supports a number of APIs to list the directory contents. For instance, we can use the Path.iterdir, os.scandir, os.walk, Path.rglob, or os.listdir functions. 
Directory in use: gfg
 
 os.listdir() method gets the list of all files and directories in a specified directory. By default, it is the current directory. Beyond the first level of folders, os.listdir() does not return any files or folders.
Syntax: os.listdir(path)
Parameters:
Path of the directory
Return Type: returns a list of all files and directories in the specified path
Example 1: Get all the list files in a Directory
Python
# import OS moduleimport os # Get the list of all files and directoriespath = "C://Users//Vanshi//Desktop//gfg"dir_list = os.listdir(path) print("Files and directories in '", path, "' :") # prints all filesprint(dir_list)
Output:
  
Example 2: To get only .txt files.
Python3
# import OSimport os for x in os.listdir():    if x.endswith(".txt"):        # Prints only text file present in My Folder        print(x)
 Output:
 OS.walk() generates file names in a directory tree. This function returns a list of files in a tree structure. The method loops through all of the directories in a tree.
Syntax: os.walk(top, topdown, onerror, followlinks)
top: It is the top directory from which you want to retrieve the names of the component files and folders.
topdown: Specifies that directories should be scanned from the top down when set to True. If this parameter is False, directories will be examined from the top down.
onerror: It provides an error handler if an error is encountered 
followlinks: if set to True, visits folders referenced by system links 
Return: returns the name of every file and folder within a directory and any of its subdirectories.
Python3
# import OS moduleimport os # This is my pathpath = "C://Users//Vanshi//Desktop//gfg" # to store files in a listlist = [] # dirs=directoriesfor (root, dirs, file) in os.walk(path):    for f in file:        if '.txt' in f:            print(f)
Output:
 os.scandir() is supported for Python 3.5 and greater. 
Syntax: os.scandir(path = ‘.’)
Return Type: returns an iterator of os.DirEntry object.
Python3
# import OS moduleimport os # This is my pathpath = "C://Users//Vanshi//Desktop//gfg" # Scan the directory and get# an iterator of os.DirEntry objects# corresponding to entries in it# using os.scandir() methodobj = os.scandir() # List all files and directories in the specified pathprint("Files and Directories in '% s':" % path)for entry in obj:    if entry.is_dir() or entry.is_file():        print(entry.name)
Output:
The glob module is used to retrieve files/path names matching a specified pattern. 
glob() method: With glob, we can use wild cards (“*, ?, [ranges]) to make path retrieval more simple and convenient.
Example:
Python3
import glob # This is my pathpath = "C:\\Users\\Vanshi\\Desktop\\gfg" # Using '*' patternprint('\nNamed with wildcard *:')for files in glob.glob(path + '*'):    print(files) # Using '?' patternprint('\nNamed with wildcard ?:')for files in glob.glob(path + '?.txt'):    print(files)  # Using [0-9] patternprint('\nNamed with wildcard ranges:')for files in glob.glob(path + '/*[0-9].*'):    print(files)
Output:
 iglob() method can be used to print filenames recursively if the recursive parameter is set to True.
Syntax: glob.glob(pathname, *, recursive=False)
Example:
Python3
import glob # This is my pathpath = "C:\\Users\\Vanshi\\Desktop\\gfg**\\*.txt"  # It returns an iterator which will# be printed simultaneously.print("\nUsing glob.iglob()") # Prints all types of txt files present in a Pathfor file in glob.iglob(path, recursive=True):    print(file)
Output:
sooda367
surajkumarguptaintern
python-file-handling
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.