usertest usertest - 1 year ago 36
Python Question

Find all files in directory with extension .txt in Python

How can I find all files in directory with the extension

in python?


You can use glob:

import glob, os
for file in glob.glob("*.txt"):

or simply os.listdir:

import os
for file in os.listdir("/mydir"):
    if file.endswith(".txt"):

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

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