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.
This is because
listdir()returns the names of the files in/foo/bar. When you later doos.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 soisdir()returnsFalse..Use the complete pathname. Best way is to use
os.path.join, e.g.,os.path.isdir(os.path.join('/foo/bar', f)).