Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
579 views
in Technique[技术] by (71.8m points)

python - Force Overwrite in Os.Rename

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 replaced by the Tests.txt file (that was also renamed to Tests.csv).

os.rename("C:UsersTest.txt","C:UsersTests.csv");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since Python 3.3, there is now a standard cross-platform solution, os.replace:

Rename the file or directory src to dst. If dst is a directory, OSError will be raised. If dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement).

Availability: Unix, Windows.

New in version 3.3.

However, contrary to the documentation, on Windows it's not guaranteed to be atomic (in Python 3.4.4). That's because internally it uses MoveFileEx on Windows, which doesn't make such a guarantee.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...