Skip to content

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)
Code language: Python (python)

Option 2 – Using os.walk()

import os dirPath = r"/your/directory/path/" result = next(os.walk(dirPath))[2] print(result)
Code language: Python (python)

Option 3 – Using glob.glob()

import glob dirPathPattern = r"/your/directory/path/*.*" result = glog.glob(dirPathPattern) print(result)
Code language: Python (python)

See also  When your Python code is much faster with PyPy
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x