python - 在 Os.Rename 中强制覆盖

标签 python

如果另一个文件已经存在,是否可以强制重命名 os.rename 覆盖另一个文件?例如,在下面的代码中,如果文件 Tests.csv 已经存在,它将被 Tests.txt 文件替换(该文件也被重命名为 Tests.csv)。

os.rename("C:\Users\Test.txt","C:\Users\Tests.csv");

最佳答案

从 Python 3.3 开始,现在有一个标准的跨平台解决方案,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.

但是,与文档相反,在 Windows 上它不能保证是原子的(在 Python 3.4.4 中)。那是因为 internally它使用 MoveFileEx在 Windows 上,它不做这样的保证。

关于python - 在 Os.Rename 中强制覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8107352/

相关文章:

Python 安装程序 : "Error writing to file C:\Python27\pythonw.exe"

python - 如何从 asn1 数据文件中提取数据并将其加载到数据框中?

python - 如何创建键: column_name and value : unique values in column in python from a dataframe的字典

python - 将 datetime.time 转换为秒

python - 包含引号的文本的句子标记化

python - 创建 CKAN 扩展错误 : No such command 'create'

python - 在 python 中检查数据描述符属性

python - Pandas 条件格式不显示背景颜色。 (没有错误)

python - 在数据库中已有数据之后添加的 UUID 字段。有没有办法为现有数据填充 UUID 字段?

python - "__str__ returned non-string (type int)"错误