usertest usertest - 2 years ago 98
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?

Answer Source

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))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download