How to Get All Files in a Directory in Python

If you need to get all the files in a directory using Python, then you can do the following:

Option 1 – Using os.listdir()

import os

dirPath = r"/your/directory/path/"
result = [f for f in os.listdir(dirPath) if os.path.isfile(os.path.join(dirPath, f))]

print(result)

Option 2 – Using os.walk()

import os

dirPath = r"/your/directory/path/"
result = next(os.walk(dirPath))[2]

print(result)

Option 3 – Using glob.glob()

import glob

dirPathPattern = r"/your/directory/path/*.*"
result = glog.glob(dirPathPattern)

print(result)