How can I find all files in directory with the extension .txt in python?
Thanks.
UPDATE: Thanks everyone, wide variety of examples for the next person that searches for this.
How can I find all files in directory with the extension .txt in python?
Thanks.
UPDATE: Thanks everyone, wide variety of examples for the next person that searches for this.
Use glob.
>>> import glob
>>> glob.glob('./*.txt')
['./outline.txt', './pip-log.txt', './test.txt', './testingvim.txt']
Something like that should do the job
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith('.txt')
print file
you can use glob
import glob
import os
os.chdir("/mydir")
for files in glob.glob("*.txt"):
print files
or simple os.listdir
import os
os.chdir("/mydir")
for files in os.listdir("."):
if files.endswith(".txt"):
print files
or if you want to traverse directory
import os
for r,d,f in os.walk("/mydir"):
for files in f:
if files.endswith(".txt"):
print os.path.join(r,files)
Something like this will work:
>>> import os
>>> path = '/usr/share/cups/charmaps'
>>> text_files = [f for f in os.listdir(path) if f.endswith('.txt')]
>>> text_files
['euc-cn.txt', 'euc-jp.txt', 'euc-kr.txt', 'euc-tw.txt', ... 'windows-950.txt']
I like os.walk():
import os, os.path
for root, dirs, files in os.walk(dir):
for f in files:
fullpath = os.path.join(root, f)
if os.path.splitext(fullpath)[1] == '.txt':
print fullpath
Or with generators:
import os, os.path
fileiter = (os.path.join(root, f)
for root, _, files in os.walk(dir)
for f in files)
txtfileiter = (f for f in fileiter if os.path.splitext(f)[1] == '.txt')
for txt in txtfileiter:
print txt
Here's more versions of the same that produce slightly different results:
import glob
for f in glob.iglob("/mydir/*/*.txt"): # generator, search immediate subdirectories
print f
print glob.glob1("/mydir", "*.tx?") # literal_directory, basename_pattern
import fnmatch, os
print fnmatch.filter(os.listdir("/mydir"), "*.tx?") # include dot-files