Python BUG FileExistsError: [Errno 17] File exists: xxx

Time:2020-11-26

This is a problem I encountered, but actually it is not only my problem. In any case, reporting such an error does not depend on what development scenario you are currently in. It has nothing to do with it. The main reason for this error message is that:In the codeos.mkdir()If a new path is created, this error will be reported if the path already exists.

Python BUG FileExistsError: [Errno 17] File exists: xxx

There are three ways to modify it

Case 1: add condition judgment and run again

if not os.path.exists(training_path):
    os.mkdir(training_path)

Case 2: using try to catch exceptions

try:
    os.mkdir(training_dir)
except OSError:
    pass

Case 3: delete the previous path before creating a path

if os.path.exists(training_path):
    #Recursively delete all subfolders and sub files under the folder
    shutil.rmtree(training_path)
os.mkdir(training_path)

You can refer to this onestackoverflow

This work adoptsCC agreementThe author and the link to this article must be indicated in the reprint


Don’t try to finish a marathon by sprinting 100 meters.