2

I have listed all directories and files of a given path by using os.listdir()

I want to see the element in the list is a file or directory, what should I do?

Mostafa Talebi
  • 8,825
  • 16
  • 61
  • 105

3 Answers3

3

Use the built in os library as well:

os.path.isdir()

os.path.isfile()

Example:

import os

root = "C:\\"
for item in os.listdir(root):
    if os.path.isfile(os.path.join(root, item)):
        print item
CasualDemon
  • 5,790
  • 2
  • 21
  • 39
2

Use os.path.isdir.

And always beware race conditions.

Mike Graham
  • 73,987
  • 14
  • 101
  • 130
0

Using os.walk you get the filtering between files and directories for free and you can also process the directory recursively.

for root, dirs, files in os.walk(root_path):
  process_dirs(dirs)
  process_files(files)
  break # If you only want to process the first level or take a look a the commend below
El Bert
  • 2,958
  • 1
  • 28
  • 36
  • However if you only care about the top directory that would be a lot slower and require more work, [for example](http://stackoverflow.com/questions/229186/os-walk-without-digging-into-directories-below). – CasualDemon Mar 11 '14 at 15:25