3

So I'm sure this is a stupid question, but I've looked through Python's documentation and attempted a couple of Google codes and none of them has worked.

It seems like the following should work, but it returns "False" for In my directory /foo/bar I have 3 items: 1 Folder "[Folder]", 1 file "test" (no extension), and 1 file "test.py".

I'm look to have a script that can distinguish folders from files for a bunch of functions, but I can't figure out anything that works.

#!/usr/bin/python
import os, re
for f in os.listdir('/foo/bar'):
    print f, os.path.isdir(f)

Currently returns false for everything.

Roman Bodnarchuk
  • 29,461
  • 12
  • 59
  • 75
user
  • 555
  • 3
  • 6
  • 21

3 Answers3

6

This is because listdir() returns the names of the files in /foo/bar. When you later do os.path.isdir() on one of these, the OS interprets it relative to the current working directory which is probably the directory your script is in, not /foo/bar, and it probably does not contain a directory of the specified name. A path that doesn't exist is not a directory and so isdir() returns False..

Use the complete pathname. Best way is to use os.path.join, e.g., os.path.isdir(os.path.join('/foo/bar', f)).

kindall
  • 178,883
  • 35
  • 278
  • 309
2

You might want to use os.walk instead: http://docs.python.org/library/os.html#os.walk

When it returns the contents of the directory, it returns files and directories in separate lists, negating the need for checking.

So you could do:

import os

root, dirs, files = next(os.walk('/foo/bar'))

print 'directories:', dirs
print 'files:', files
Acorn
  • 49,061
  • 27
  • 133
  • 172
0

I suppose that os.path.isdir(os.path.join('/foo/bar', f)) should work.

Roman Bodnarchuk
  • 29,461
  • 12
  • 59
  • 75