How to list files in directory in Python

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.

Syntax

os.listdir(path)

Parameters

path (optional) : path of the directory

Return value

The listdir() method returns the list of all files and directories in the specified path.

Example

import os


path = "/Users/krunallathiya/Desktop/Code/R"
files = os.listdir(path)
print("Files and Directories are")
for i in files:
  print(i)

Output

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:

  1. root: Current path
  2. dirs: Directories in the current path
  3. files: Files in the current path

Syntax

os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])

Parameters

  1. top − Each directory rooted at the directory yields 3-tuples, i.e., (dirpath, dirnames, filenames)
  2. 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.
  3. onerror − The oneerror can display an error to continue with the walk or raise an exception to abort a walk.
  4. followlinks − If set to True, it visits directories pointed to by symlinks.

Example

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)

Output

data.R
Pro.R

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.

Syntax

os.scandir(path = ‘.’)

Parameters

A path-like object represents the file system path.

Example

import os

path = "/Users/krunallathiya/Desktop/Code/R"
files = os.scandir(path)
for f in files:
  print(f)

Output

<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")) 

Conclusion

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.

 

Leave a Comment