How to List All Files of a Directory in Python

Created
Modified

Using os.listdir Method

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order, and does not include the special entries '.' and '..' even if they are present in the directory. See the following example:

#!/usr/bin/python3
# -*- coding: utf8 -*-

# Import module
import os

path = "."
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
print(files)
['demo.py', 'start.sh', 'file.txt']

Using os.walk Method

Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

#!/usr/bin/python3
# -*- coding: utf8 -*-

# Import module
import os

path = "."
files = next(os.walk(path), (None, None, []))[2]
print(files)
['demo.py', 'start.sh', 'file.txt']

Using glob Module

The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, although results are returned in arbitrary order. For example,

#!/usr/bin/python3
# -*- coding: utf8 -*-

# Import module
import glob

txt = "*.txt"
files = glob.glob(txt)
print(files)
['file.txt']

Related Tags