In this article, we will cover how do we list all files in a directory in python.
What is a directory?
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
Method 1: Os Module
- 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 module import os # Get the list of all files and directories dir_list = os.listdir(path) print ( "Files and directories in '" , path, "' :" ) # prints all files print (dir_list) |
Output:
Example 2: To get all the files, and no folders.
Python3
import os print ( "Python Program to print list the files in a directory." ) Direc = input (r "Enter the path of the folder: " ) print (f "Files in the directory: {Direc}" ) files = os.listdir(Direc) files = [f for f in files if os.path.isfile(Direc + '/' + f)] #Filtering only the files. print ( * files, sep = "\n" ) #os.getcwd() gives us the current working directory, and os.listdir lists the director |
Example 2.5: To get only .txt files.
Python3
# import OS import 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 module import os # This is my path # to store files in a list list = [] # dirs=directories for (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 module import os # This is my path # Scan the directory and get # an iterator of os.DirEntry objects # corresponding to entries in it # using os.scandir() method obj = os.scandir() # List all files and directories in the specified path print ( "Files and Directories in '% s':" % path) for entry in obj: if entry.is_dir() or entry.is_file(): print (entry.name) |
Output:
Method 2: Using glob module
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 path path = "C:\\Users\\Vanshi\\Desktop\\gfg" # Using '*' pattern print ( '\nNamed with wildcard *:' ) for files in glob.glob(path + '*' ): print (files) # Using '?' pattern print ( '\nNamed with wildcard ?:' ) for files in glob.glob(path + '?.txt' ): print (files) # Using [0-9] pattern print ( '\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.iglob(pathname, *, recursive=False)
Example:
Python3
import glob # This is my path path = "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 Path for file in glob.iglob(path, recursive = True ): print ( file ) |
Output: