The Python Oracle

Find all files in a directory with extension .txt in Python

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Peaceful Mind

--

Chapters
00:00 Question
00:22 Accepted answer (Score 3041)
00:54 Answer 2 (Score 339)
01:07 Answer 3 (Score 217)
01:21 Answer 4 (Score 169)
02:05 Thank you

--

Full question
https://stackoverflow.com/questions/3964...

Accepted answer links:
[glob]: https://docs.python.org/2/library/glob.h...
[os.listdir]: https://docs.python.org/2/library/os.htm...
[os.walk]: https://docs.python.org/2/library/os.htm...

Answer 2 links:
[glob]: http://docs.python.org/library/glob.html

Answer 4 links:
[pathlib]: https://docs.python.org/library/pathlib....
[glob]: https://docs.python.org/library/pathlib....
[pathlib]: https://pypi.python.org/pypi/pathlib/
[pathlib2]: https://pypi.python.org/pypi/pathlib2/

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #fileio

#avk47



ACCEPTED ANSWER

Score 3174


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))



ANSWER 2

Score 368


Use glob.

>>> import glob
>>> glob.glob('./*.txt')
['./outline.txt', './pip-log.txt', './test.txt', './testingvim.txt']



ANSWER 3

Score 224


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)



ANSWER 4

Score 163


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']