Bootstrap FreeKB - Python (Scripting) - Determine if an object is a file or directory (os.path.isfile isdir)
Python (Scripting) - Determine if an object is a file or directory (os.path.isfile isdir)

Updated:   |  Python (Scripting) articles

In a Python script, the os.path module can be used to determine if a path is a file or a directory. You will typically want to also first use os.path.exists to determine if the path exists.

#!/usr/bin/python
import os.path
if os.path.exists("/usr/local/foo"):
  print "/usr/local/foo exists"
  if os.path.isfile("/usr/local/foo"):
    print "/usr/local/foo is a file"
  elif os.path.isdir("/usr/local/foo"):
    print "/usr/local/foo is a directory"
else:
  print "/usr/local/foo does not exist"

 

Better yet, using a variable.

#!/usr/bin/python3
import os.path
foo = "/usr/local/foo"
if os.path.exists(foo):
  print(f"{foo} exists")
  if os.path.isfile(foo):
    print(f"{foo} is a file")
  elif os.path.isdir(foo):
    print(f"{foo} is a directory")
else:
  print(f"{foo} does NOT exist")

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 0a72cc in the box below so that we can be sure you are a human.