Remove directories from os.listdir output

Steve Purcell stephen_purcell at
Sun Feb 18 12:39:10 CET 2001

Fernando Rodríguez wrote:
> Hi!
> 	I need to filter out all the diretories of the list returned by
> os.listdir(). How can I tell if an entry of that list is a dir or a regular
> file? O:-)

Use os.path.isdir():

>>> import os
>>> def listdir_files_only(directory):
...     contents = os.listdir(directory)
...     return filter(lambda f,d=directory: not os.path.isdir(os.path.join(d,f)), contents)
>>> listdir_files_only('/tmp')
['python-sHAOTT', 'python-sHASlX', 'python-sHATtS']


Steve Purcell, Pythangelist
Get testing at
Get servlets at
"Even snakes are afraid of snakes." -- Steven Wright

More information about the Python-list mailing list