[Python] Create a new file, moving an existing file out of the way if needed

Discussão em 'Python' iniciado por Stack, Abril 2, 2025.

  1. Stack

    Stack Membro Participativo

    What is the best way to create a new file in Python, moving if needed an existing file with the same name to a different path?

    While you could do

    if os.path.exists(name_of_file):
    os.move(name_of_file, backup_name)
    f = open(name_of_file, "w")


    that has TOCTOU issues (e.g. multiple processes could try and create the file at the same time). Can I avoid those issues using only the standard library (preferably), or is there a package which handles this.

    You can assume a POSIX file system.

    Continue reading...

Compartilhe esta Página