Sorting Directories from files in a os.listdir??
Peter Otten
__peter__ at web.de
Thu Apr 10 08:33:16 EDT 2008
Scott David Daniels wrote:
>> I'd like to read the filenames in a directory, but not the
>> subdirectories, os.listdir() gives me everything... how do I separate
>> the directory names from the filenames? Is there another way of doing
>> this?
>>
>> Thanks!
>
> import os
> base, files, dirs = iter(os.walk(dirname)).next()
> # now files is files and dirs is directories (and base == dirname)
>>> import os
>>> os.listdir(".")
['fifo', 'dir', 'file'] # a fifo, a directory, and a file
>>> w = os.walk(".")
>>> w is iter(w) # calling iter() is a noop here
True
>>> w.next()
('.', ['dir'], ['fifo', 'file']) # base, dirs, files; everything that is not
# a directory goes into the files list
Peter
More information about the Python-list
mailing list