Determining whether it's a file or a directory?

Peter Otten __peter__ at web.de
Fri Oct 8 05:50:59 EDT 2004


Dfenestr8 wrote:

> os.listdir("path") returns the names of all the items in a directory ok,
> but I need to know whether the item is a file or a directory.
> 
> Can anybody tell me how this could be done?

The standard way would be to perform

os.path.isdir(os.path.join(path, dir_or_file))

on the item in question, but

>>> import os
>>> for path, dirs, files in os.walk("path"):
...     break
...
>>> dirs
['only', 'directories']
>>> files
['some', 'files']
>>>

gives you directories and files in separate lists.

Peter




More information about the Python-list mailing list