Computer >> Computer tutorials >  >> Programming >> Python

How to find all files in a directory with extension .txt in Python?


You can use the os.listdir method to get all directories and files in a directory. Then filter the list to get only the files and check their extensions as well.

For example

>>> import os
>>> file_list = [f for f in os.listdir('.') if os.path.isfile(os.path.join('.', f)) and f.endswith('.txt')]
>>> print file_list
['LICENSE.txt', 'NEWS.txt', 'README.txt']

The endswith method is a member of string class that checks if a string ends with a certain suffix.

You can also use the glob module to achieve the same:

>>> import glob, os
>>> file_list = [f for f in glob.glob("*.txt")]
>>> print file_list
['LICENSE.txt', 'NEWS.txt', 'README.txt']