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