python - specifically handle file exists exception

后端 未结 2 1414
一向
一向 2021-02-05 05:05

I have come across examples in this forum where a specific error around files and directories is handled by testing the errno value in OSError (or

2条回答
  •  你的背包
    2021-02-05 05:22

    According to the code print ..., it seems like you're using Python 2.x. FileExistsError was added in Python 3.3; You can't use FileExistsError.

    Use errno.EEXIST:

    import os
    import errno
    
    try:
        os.mkdir(folderPath)
    except OSError as e:
        if e.errno == errno.EEXIST:
            print('Directory not created.')
        else:
            raise
    

提交回复
热议问题