Skip to content

Instantly share code, notes, and snippets.

@greentornado
Last active July 20, 2018 08:45
Show Gist options
  • Save greentornado/06b076544cd118bf4de6e0c47a9809be to your computer and use it in GitHub Desktop.
Save greentornado/06b076544cd118bf4de6e0c47a9809be to your computer and use it in GitHub Desktop.
Find all files in a directory with extension .txt in Python
import os
print(os.path.isdir("/home/el"))
print(os.path.exists("/home/el/myfile.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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment