[Tutor] Howto test if something is a directory?

Michael P. Reilly arcege@shore.net
Sun, 23 Jan 2000 14:52:06 -0500 (EST)

> Hash: SHA1
> I want to take the output of os.listdir() and test each entry to see
> if it is a directory, or a regular file. What is the best way to do
> this? 
> I would prefer a method that works on Windows, Mac and UNIX, but if it
> is OS-dependant, UNIX is by far the most important.
> Sorry if this is in the standard documentation, I couldn't find it.

The best way that I've found is:

import os

for fname in os.listdir(dirname):
  file = os.path.join(dirname, fname):
  if os.path.isdir(file):
    print fname, 'is a directory'
  elif os.path.islink(file):
    print fname, 'is a symbolic link'
  elif os.path.isfile(file):
    print fname, 'is a file'

Unfortunately, there isn't a nice way to distinguish between other
specific types of files (block and character devices, FIFO and
sockets) without looking at the output of os.stat().


| Michael P. Reilly, Release Engineer | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |