How can I create a file in python?

Options
Pernelle Marone-Hitz
Pernelle Marone-Hitz Member, Moderator, Employee Posts: 813
First Comment First Anniversary Ansys Employee Solution Developer Community of Practice Member

How can I check if a file exists and create it if it doesn't?

Tagged:

Answers

  • Pernelle Marone-Hitz
    Pernelle Marone-Hitz Member, Moderator, Employee Posts: 813
    First Comment First Anniversary Ansys Employee Solution Developer Community of Practice Member
    Answer ✓
    Options

    The following function can be used:

        import os
        def CreateFile(filePath):
            '''
            create the file filePath if not existing
            :param filePath: path of file
            ''' 
            try:
                if not (filePath and os.path.isfile(filePath)): # if the file doesn't exist, let's create it
                    open(filePath, 'a').close()
            except:
                ExtAPI.Log.WriteError("Error : Exception in CreateFile()")