views:

503

answers:

3

When using os.listdir method I need to tell which item in the resulting list is a directory or just a file.

I've faced a problem when I had to go through all the directories in this list, and then add a file in every single directory.

Is there a way to go through this list and remove all files from it? If it isn't possible to do with os.listdir, what method should I use instead?

Thanks.

+7  A: 

Use os.path.isdir to filter out the directories. Possibly something like

dirs = filter(os.path.isdir, os.listdir('/path'))
for dir in dirs:
    # add your file
David Zaslavsky
Thanks for quick answer! I checked help(os.path) and found out that maybe isfile(path) would be usefull too. isdir(s) Return true if the pathname refers to an existing directory. isfile(path) Test whether a path is a regular file
Anatoliy
Don't forget the test for if a file is a soft link: islink, and ismount for if a file is the mountpoint for a device.
Matthew Schinckel
+2  A: 

dirs = filter(os.path.isdir, os.listdir('/path'))

Note this won't work unless '/path' is the current working directory. os.listdir() returns leafnames, so you'll be asking “os.path.isdir('file.txt')”, and if the current directory is elsewhere you'll be looking at the wrong 'file.txt'.

os.path.join() should be used on the output of os.listdir() to obtain a complete filename.

children= [os.path.join('/path', child) for child in os.listdir('/path')]
directories= filter(os.path.isdir, children)
bobince
I've done it this way. dir = os.listdir(dir) i=len(dir)-1 while i>-1: if os.path.isfile(odir+'\\'+dir[i]): del dir[i] i = i-1where dir is user defined directory. Works just fine.
Anatoliy
Forgot to mention: odir = dir #'odir' stands for 'original directory'So 'odir' contains user defined directory, after 'dir' is changed to a list. P.S. Is there any way to edit comments? O_o
Anatoliy
You delete them and re-post, pretending nothing happened :-)
bobince
Anyhow... ‘odir+'\\'+dir[i]’ will work fine on Windows, but os.path.join() is the explicit, cross-platform way of doing it. Not that it probably matters for a script you're only going to use once...
bobince
It actually matters, because I myself use Linux from time to time and some friends, i just didn't think of right way to write it at first. I really should change it to os.path.join, thank you for mentioning.
Anatoliy
+2  A: 

This might be faster:

current, dirs, files = os.walk('/path').next()

The list of directories will be in the dirs variable.

nosklo
Agreed! I will try it also, thanks.
Anatoliy