Distinguishing files from directories
So, I'm sure this is a stupid question, but I looked through the Python documentation and tried several google codes and none of them worked.
The following seems to work, but it returns "False" for In my / foo / bar directory I have 3 items: 1 "[Folder]" folder, 1 "Test" file (no extension), and 1 "test" file. py ".
I want to have a script that can differentiate 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)
It currently returns false for everything.
source to share
This is because it listdir()
returns filenames in /foo/bar
. When you later do os.path.isdir()
on one of them, the OS interprets it relative to the current working directory, which is probably the directory the script is in, not /foo/bar
, and it probably does not contain the directory specified by the name. A path that doesn't exist is not a directory, so it isdir()
returns False.
.
Use the full path. The best way is to use os.path.join
eg os.path.isdir(os.path.join('/foo/bar', f))
.
source to share
You can use instead os.walk
: http://docs.python.org/library/os.html#os.walk
When it returns the contents of a directory, it returns files and directories in separate lists, which negates the need to check.
So you can do:
import os
root, dirs, files = next(os.walk('/foo/bar'))
print 'directories:', dirs
print 'files:', files
source to share