Problem
In Python, how can I find all the files in a directory with the extension.txt?
Asked by usertest
Solution #1
You can use the command 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))
Alternatively, if you wish to walk through a 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))
Answered by ghostdog74
Solution #2
Use glob.
>>> import glob
>>> glob.glob('./*.txt')
['./outline.txt', './pip-log.txt', './test.txt', './testingvim.txt']
Answered by Muhammad Alkarouri
Solution #3
Something along those lines should suffice.
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith('.txt'):
print(file)
Answered by Adam Byrtek
Solution #4
Something along these lines will suffice:
>>> 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']
Answered by Seth
Solution #5
You may simply use pathlibs glob 1: to accomplish this.
import pathlib
list(pathlib.Path('your_directory').glob('*.txt'))
Alternatively, in a loop:
for txt_file in pathlib.Path('your_directory').glob('*.txt'):
# do something with "txt_file"
You can use.glob(‘**/*.txt’) to make it recursive.
1In Python 3.4, the pathlib module was added to the standard library. However, back-ports of that module are available for older Python versions (through conda or pip): pathlib and pathlib2.
Answered by MSeifert
Post is based on https://stackoverflow.com/questions/3964681/find-all-files-in-a-directory-with-extension-txt-in-python