How can I create a file in python?

Pernelle Marone-Hitz
Pernelle Marone-Hitz Member, Moderator, Employee Posts: 871
100 Answers 500 Comments 250 Likes First Anniversary
✭✭✭✭

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: 871
    100 Answers 500 Comments 250 Likes First Anniversary
    ✭✭✭✭
    Answer ✓

    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()")