Skip to content
Related Articles

Related Articles

Improve Article

Python – List Files in a Directory

  • Last Updated : 03 Jun, 2021

Directory also sometimes known as a folder are unit organizational structure in 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.

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:

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:

  

  Program 2: 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.  

 

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:



 
 

Syntax:

os.scandir(path = ‘.’)

Return Type: returns an iterator of os.DirEntry object.

Example:

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

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.

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.glob(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:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :