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.

+3


source to share


3 answers


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

.

+6


source


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

      

+2


source


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

should work.

0


source







All Articles