Bootstrap FreeKB - Python (Scripting) - Determine if a file or directory exists
Python (Scripting) - Determine if a file or directory exists

Updated:   |  Python (Scripting) articles

os.path.exists can be used to determine if a file or directory exists and os.mkdir can be used to create the directory if it does not exist.

#!/usr/bin/python
import os.path
if os.path.exists("/usr/local/foo"):
  print("/usr/local/foo exists")
else:
  print("/usr/local/foo does not exist")
  os.mkdir("/usr/local/foo")

 

Or like this, using False.

#!/usr/bin/python
import os.path
if os.path.exists("/usr/local/foo") == False:
  print("/usr/local/foo does not exist")
  os.mkdir("/usr/local/foo")
else:
  print("/usr/local/foo exists")

 

Or like this, using not.

#!/usr/bin/python
import os.path
if not os.path.exists("/usr/local/foo"):
  print("/usr/local/foo does not exist")
  os.mkdir("/usr/local/foo")
else:
  print("/usr/local/foo exists")

 

Or, sometimes you may want to go with os.path.abspath.

#!/usr/bin/python3
import os.path
foo = "/usr/local/foo"
if os.path.abspath(foo):
  print(f"{foo} exists")
else:
  print(f"{foo} does NOT exist")
  os.mkdir("/usr/local/foo")

 

Better yet, using a variable.

#!/usr/bin/python3
import os.path
foo = "/usr/local/foo"
if os.path.exists(foo):
  print(f"{foo} exists")
else:
  print(f"{foo} does NOT exist")

 

Or, for best performancescandir can be used.

#!/usr/bin/python
import os

for entry in os.scandir('/usr/local/foo'):
  if not entry.name.startswith('.') and entry.is_dir():
    print(entry.name)

 




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 aef8c3 in the box below so that we can be sure you are a human.