Check If Directory Exists Python If Not Create

Check If Directory Exists Python If Not Create

To check is the directory is existed or not we use python os module. With python os module we can is the directory existed or not. If not we can create directory with python os module.

Check If Directory Exists Python If Not Create

import os
x=r'C:\Users\enaknar\Desktop\pycharm\devops'

if os.path.exists(x):
    if os.path.isfile(x):
        print("file is existed")
    elif os.path.isdir(x):
        print("directory is existed")

else:
    print("directory is not existed and creating a new directory")
    os.mkdir(x)

 

os.path.exists(): os.path.exists() will check is that path existed or not.

os.path.isfile(): os.path.isfile() will check is that file or not

os.path.isdir(): os.path.isdir() will check is that directory or not

os.mkdir(): with os.mkdir we can create new directory

  • Check If Directory Exists Python If Not Create
  • check if the directory exists in python
  • python check if the directory exists or not

Leave a Reply

Your email address will not be published. Required fields are marked *