How can I find all the files in a directory having the extension .txt
in python?
locate command syntax: Similarly, you can follow the syntax of locate command for finding all files with any specific extension such as “. txt.”
You can use glob
:
import glob, os os.chdir("/mydir") for file in glob.glob("*.txt"): print(file)
or simply os.listdir
:
import os for 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 os for 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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With