how to check if a file is a directory or regular file in python?

Python

Python Problem Overview


How do you check if a path is a directory or file in python?

Python Solutions


Solution 1 - Python

os.path.isfile("bob.txt") # Does bob.txt exist?  Is it a file, or a directory?
os.path.isdir("bob")

Solution 2 - Python

use os.path.isdir(path)

more info here http://docs.python.org/library/os.path.html

Solution 3 - Python

Many of the Python directory functions are in the os.path module.

import os
os.path.isdir(d)

Solution 4 - Python

An educational example from the stat documentation:

import os, sys
from stat import *

def walktree(top, callback):
    '''recursively descend the directory tree rooted at top,
       calling the callback function for each regular file'''

    for f in os.listdir(top):
        pathname = os.path.join(top, f)
        mode = os.stat(pathname)[ST_MODE]
        if S_ISDIR(mode):
            # It's a directory, recurse into it
            walktree(pathname, callback)
        elif S_ISREG(mode):
            # It's a file, call the callback function
            callback(pathname)
        else:
            # Unknown file type, print a message
            print 'Skipping %s' % pathname

def visitfile(file):
    print 'visiting', file

if __name__ == '__main__':
    walktree(sys.argv[1], visitfile)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionduhhunjonnView Question on Stackoverflow
Solution 1 - PythonJesse JashinskyView Answer on Stackoverflow
Solution 2 - PythonJordanView Answer on Stackoverflow
Solution 3 - PythonChris B.View Answer on Stackoverflow
Solution 4 - PythonYuppieNetworkingView Answer on Stackoverflow