All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Python Create File If Not Exists

Last Updated : Mar 11, 2024

Python Create File If Not Exists

In this article we will show you the solution of python create file if not exists, the ability to work with files is a crucial skill that is required for any developer, regardless of the language in which he works.

A developer must ensure that such programs and applications don't create a new file every time they are executed whenever they are writing these programs and applications.

The file should not be created first, but rather if one does not exist, it should be created.

We will now discuss the idea of how to create a file if it does not exist in python with an example.

Step By Step Guide On Python Create File If Not Exists :-

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’t be read ")
    except PermissionError:
        ret = False
        print("Don’t 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 + "/tc_v1.txt"
    fileExist = checkFileExistByPathlib(baseurl)
    if(not fileExist):
        makeFreshFile(baseurl)
        setFilePermission(baseurl)
    checkFileStatusByOSAccess(baseurl)
  1. In order to perform file and folder operations, you must first import the necessary modules and libraries. It imports the operating system, statistics, and path library modules.
  2. In order to verify the existence of a file or folder using os.path.exists, the checkFileExistByOSPath function is defined. Whether the path exists is checked with the function and a True result is returned if it does. A message indicating that it is a file is displayed if the path exists and is a file; otherwise, it is a directory if the path does not exist.
  3. Using the open function and exception handling, the checkFileExistByException function determines whether or not a file or folder exists. As soon as the file is opened, the content is read and a message is displayed stating that the file exists and its contents have been read. Functions that display error messages display an empty string if the file does not exist. A message telling the user that the file cannot be read will appear if there is an IO error.
  4. A file or folder's existence can be verified by calling checkFileExistByPathlib using the pathlib.Path.exists function. Returns True if the path exists if the function checks if the path exists. When the path is a file, the function displays a message indicating that it is a file. Functions that return a directory display a message as an indication that the path is one.
  5. The checkFileStatusByOSAccess function verifies the status of the file or folder using the os.access function. The function checks if the file exists and is readable, writable, or executable. In the event that the file is readable, the function prints a message indicating that it is readable. Functions that check for writability will print a message that shows that the file is writable. An executable file is detected by the function and an executable message is printed.
  6. Whenever a file does not exist, the makeFreshFile method creates a new one. A file object is created using the open function and some text is written to it, along with a message letting the user know the file has been created.
  7. When there is no folder in the underlying directory, the createNewFolder function creates a new folder. By using the checkFileExistByOSPath function, the function determines whether a folder already exists, and if it doesn't, it creates a new folder using the os.mkdir function. A message indicating that the folder has been created is displayed by the function.
  8. Setting file permissions through setFilePermission calls the os.chmod function is available in the setFilePermission function. By setting executable and readable permissions, the file can be accessed and executed.
  9. As part of the main function, a folder named "test" is created using the createNewFolder function.
  10. In this case, the baseurl variable can be initialized with the path to the new file.
  11. Using the checkFileExistByPathlib function, the fileExist variable is initialized.
  12. To create a new file, the makeFreshFile function is called if the file does not exist. In order to set file permissions, the setFilePermission function is called.
  13. When the file status needs to be verified, checkFileStatusByOSAccess is called.
  14. A final step is executing the code and displaying the results.

Conclusion :-

As a result, we have successfully learned how to create a file if it does not exist in python with an example.

When inserting a single string into a text file, we use the baseurl method; when inserting multiple strings, we use the writelines() method.

I hope this article on python create file if not exists helps you and the steps and method mentioned above are easy to follow and impleement.

Author Image About Amruta

Amruta is an Experienced web developer with 4 years for experience she completed her master's with MCA and passionate about programming Languages for creating technical contents like HTML, CSS, JavaScript, Java, Python, PHP, jQuery.

Follow Amruta On Linkedin 🡪