Last active
July 20, 2018 08:45
-
-
Save greentornado/06b076544cd118bf4de6e0c47a9809be to your computer and use it in GitHub Desktop.
Find all files in a directory with extension .txt in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
print(os.path.isdir("/home/el")) | |
print(os.path.exists("/home/el/myfile.txt")) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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