jesse
jesse

Reputation: 658

Distinguishing Files From Directories

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.

Upvotes: 3

Views: 1692

Answers (3)

kindall
kindall

Reputation: 184200

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)).

Upvotes: 6

Acorn
Acorn

Reputation: 50517

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

Upvotes: 2

Roman Bodnarchuk
Roman Bodnarchuk

Reputation: 29727

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

Upvotes: 0

Related Questions