python create file if not exists – How to Create File If Not Exists in Python?

Rate this post

python create file if not exists Using the open() Function and Using the touch() Method of the pathlib Module Example with demo. Using a Write mode “w” or “w+” will create a file if not exists in Python.

python create file if not exists

Create a File if Not Exists in Python – Check if File Exists. Check if File Exists using the os.path Module, using the pathlib Module. To create a file if not exists in Python, use the open() function.

Mode Description
w Write
r Read
a Append
w+ Create the file if it does not exist and then open it in write
r+ Open the file in the read and write
a+ Create the file if it does not exist and then open it in append

file = open('myfolder/pakainfodoc.txt','a+')

file = open('myfolder/pakainfodoc.txt','w+')

Free Live Chat for Any Issue

Python Create File if Not Exists Using the touch() Method of the pathlib Module

Example

from pathlib import Path

pakainfodoc = Path('myfolder/pakainfodoc.txt')
pakainfodoc.touch(exist_ok=True)
f = open(pakainfodoc)

python create file if not exists

python create file if not exists

import os

if not os.path.exists(path):
    with open(path, 'w'): 

don’t Miss : Arduino Float To String

Read Also:  html code to send email on button click

Python Create File If Not Exists Example

python create file if doesbt exist

import os, stat
import pathlib

def checkFileExistByOSPath(baseurl):

    ret = False
    if(os.path.exists(baseurl)):
        ret = True
        print(baseurl + " exist.")
        # If this is a file.
        if(os.path.isfile(baseurl)):
            print(" and it is a file.")
        # This is a directory.    
        else:
            print(" and it is a directory.")
    else:
        ret = False
        print(baseurl + " do not exist.")
        
    return ret
        
def checkFileExistByException(baseurl):
    ret = True
    try:
        newFlObj = open(baseurl, 'r')
        # Read entire file content data.
        file_data = newFlObj.read()
        print(baseurl + " exist. It's data : " + file_data)
    except FileNotFoundError:
        ret = False
        print(baseurl + " do not exist.")
    except IOError:
        ret = False
        print(baseurl + " can not be read. ")    
    except PermissionError:
        ret = False
        print("Do not have permission to read file " + baseurl)

    return ret
         
def checkFileExistByPathlib(baseurl):
    ret = True
        
    pl = pathlib.Path(baseurl)
    
    ret = pl.exists()
    
    if(ret):
        print(baseurl + " exist.")
    else:
        print(baseurl + " do not exist.")
    
    if(pl.is_file()):
        print(baseurl + " is a file.")
       
    if(pl.is_dir()):
        print(baseurl + " is a directory.")
    
    return ret

def checkFileStatusByOSAccess(baseurl):

    if(os.access(baseurl, os.F_OK)):
        print(baseurl + " exist.")
    else:
        print(baseurl + " do not exist.")
            
    if(os.access(baseurl, os.R_OK)):
        print(baseurl + " is readable.")
        
    if(os.access(baseurl, os.W_OK)):
        print(baseurl + " is writable.")    
        
    if(os.access(baseurl, os.EX_OK)):
        print(baseurl + " is executable.")

def makeFreshFile(baseurl):
    newFlObj = open(baseurl, 'w')
    newFlObj.write('File is created.')
    print(baseurl + " has been created. ")
    
def createNewFolder(baseurl):
    if(not checkFileExistByOSPath(baseurl)):
        os.mkdir(baseurl)
        print(baseurl + " has been created. ")

def setFilePermission(baseurl):
    os.chmod(baseurl, stat.S_IEXEC | stat.S_IREAD)
     
        
if __name__ == '__main__':
    file_folder = "./test"
    createNewFolder(file_folder)
    
    baseurl = file_folder + "/pakainfo_v1.txt"

    fileExist = checkFileExistByPathlib(baseurl)

    if(not fileExist):
        makeFreshFile(baseurl)
        setFilePermission(baseurl)

    checkFileStatusByOSAccess(baseurl)

Check if File Exists using the pathlib Module

Example : python create file if not exists

from pathlib import Path

if Path('pakainfo_v1.txt').is_file():
    print ("File exist")
else:
    print ("File not exist")

Download

I hope you get an idea about python create file if not exists.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.