Find all files in a directory with extension .txt in Python Find all files in a directory with extension .txt in Python python python

Find all files in a directory with extension .txt in Python


You can use glob:

import glob, osos.chdir("/mydir")for file in glob.glob("*.txt"):    print(file)

or simply os.listdir:

import osfor file in os.listdir("/mydir"):    if file.endswith(".txt"):        print(os.path.join("/mydir", file))

or if you want to traverse directory, use os.walk:

import osfor root, dirs, files in os.walk("/mydir"):    for file in files:        if file.endswith(".txt"):             print(os.path.join(root, file))


Use glob.

>>> import glob>>> glob.glob('./*.txt')['./outline.txt', './pip-log.txt', './test.txt', './testingvim.txt']


Something like that should do the job

for root, dirs, files in os.walk(directory):    for file in files:        if file.endswith('.txt'):            print(file)