Force Overwrite in Os.Rename

后端 未结 7 1648
北荒
北荒 2020-11-30 05:10

Is it possible to force a rename os.rename to overwrite another file if it already exists? For example in the code below if the file Tests.csv already exists it would be re

7条回答
  •  囚心锁ツ
    2020-11-30 06:06

    As the documentation says it's impossible to guarantee an atomic renaming operation on Windows if the file exists so what Python does is asking to do the double step os.remove + os.rename yourself, handling potential errors.

    On unix systems rename overwrites the destination if exists (because the operation is guaranteed to be atomic).

    Note that on windows it's also possible that deleting the destination file will fail even if you have permission because the file may be in use. This is another essential limitation of the windows file system and you have to handle it yourself in the code.

提交回复
热议问题