Python – List Files in a Directory
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.
- 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
Example 2: To get only .txt files.
- 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.
- os.scandir() is supported for Python 3.5 and greater.
Syntax: os.scandir(path = ‘.’)
Return Type: returns an iterator of os.DirEntry object.
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.
- iglob() method can be used to print filenames recursively if the recursive parameter is set to True.
Syntax: glob.iglob(pathname, *, recursive=False)