To list files in directories using Python, use the os.listdir() method. The os.listdir() is a built-in method that returns a list containing the names of the entries in the directory given by path. If we don’t define any directory, a list of files and directories in the current working directory will be returned.
path (optional) : path of the directory
The listdir() method returns the list of all files and directories in the specified path.
import os path = "/Users/krunallathiya/Desktop/Code/R" files = os.listdir(path) print("Files and Directories are") for i in files: print(i)
Files and Directories are data.R Rplots.pdf app.js data.py Pro.R
In this example, you can see that we printed all the files and directories in the specified directory. If no parameter is passed to listdir(), it automatically assumes the directory as the current working directory and returns the current directory files.
List files in a directory using os.walk()
The os.walk() is a built-in Python method that generates file names in a directory tree by walking through all the nested directories. The os.walk() function generates a generator containing a tuple of three values which are:
- root: Current path
- dirs: Directories in the current path
- files: Files in the current path
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
- top − Each directory rooted at the directory yields 3-tuples, i.e., (dirpath, dirnames, filenames)
- topdown − It is an optional argument, and it is True or not specified; directories are scanned from top-down. If the topdown is set to False, directories are scanned from the bottom up.
- onerror − The oneerror can display an error to continue with the walk or raise an exception to abort a walk.
- followlinks − If set to True, it visits directories pointed to by symlinks.
import os path = "/Users/krunallathiya/Desktop/Code/R" for (root, dirs, files) in os.walk(path): for f in files: if(f.endswith(".R")): print(f)
In this example, we saw how to print all the files with “.R” format inside the specific directory. We can change the “.R” to other formats like .txt, .png, .mp4, etc. to get other format files’ names. You can print dirs inside for loop to get all the subdirectories and print files to get all the types of files in the directory.
List all files in a directory using os.scandir()
The os.scandir() is a built-in Python method that extracts an iterator of os.DirEntry objects. The os.scandir() method generates an iterator that contains all the files and sub-directories inside the specified directory. It is similar to the listdir() function, but the scandir() function can be executed only if the Python version is greater than 3.5.
os.scandir(path = ‘.’)
A path-like object represents the file system path.
import os path = "/Users/krunallathiya/Desktop/Code/R" files = os.scandir(path) for f in files: print(f)
<DirEntry 'data.R'> <DirEntry 'Rplots.pdf'> <DirEntry 'app.js'> <DirEntry 'data.py'> <DirEntry 'Pro.R'>
In this example, we saw how to use the scandir() method to show all the files in the directory.
How to get files inside subdirectory in Python
To get files inside a subdirectory in Python, use the combination of os.listdir(), os.join(), and os.path.isdir() methods. If we want to search for a file inside all the subdirectories. For example, let us consider over the computer.
If we go to my computer, we can view a search bar in the right side corner of the page; if we search a file name, it checks in all the local disks. It scans all the subdirectories in all the local disks and displays all the files matching our search similarly, and now we will see how to walk through all the files’ names in all the directories and subdirectories.
import os def allFiles(dir): fi = os.listdir(dir) files =  for f in fi: fulldir = os.path.join(dir, f) if(os.path.isdir(fulldir)): files += allFiles(fulldir) else: files.append(f) print(allFiles("/Users/krunallathiya/Desktop"))
Directories are folders in which we store files. We save these files in a directory for easy access. The most common module used for accessing files or directories is the “os” module.
The OS is nothing but Operating System. There are many methods for listing the files in the directory using the os module. Some of them are: os.listdir(), os.walk(), os.scandir(), which we already saw in this tutorial.
That’s it for this tutorial.