gpt4 book ai didi

python - 静默 os.rename 失败

转载 作者:太空狗 更新时间:2023-10-29 12:02:01 29 4
gpt4 key购买 nike

假设我有两个相互硬链接(hard link)的文件:

-rw-rw-r-- 2 mparrott grp 5 Jul 28 09:38 bar
-rw-rw-r-- 2 mparrott grp 5 Jul 28 09:38 foo

然后,我在 python 中运行:

>>> import os
>>> os.rename('foo', 'bar')

我没有收到任何错误。但是,再次列出目录,我仍然看到 foo

-rw-rw-r-- 2 mparrott grp 5 Jul 28 09:38 bar
-rw-rw-r-- 2 mparrott grp 5 Jul 28 09:38 foo

这似乎正在发生,因为这些文件确实是同一个文件(inode)。但是,我仍然希望删除 foo 或引发错误。

有谁知道为什么这会悄无声息地失败?我的问题是关于实现本身,而不是如何解决问题(我使用 os.path.samefile)。我在 rhel 6.4 上。

谢谢!

最佳答案

Python 的os.rename 函数只是执行rename 系统调用。如果源和目标是同一个文件,则系统调用不执行任何操作。如果我运行 C 程序,我会得到与您的 Python 脚本相同的结果:

#include <stdio.h>

int main() {
int result = rename("foo", "bar");
printf("result = %d\n", result);
}

这会打印 result = 0 并保留两个文件。

此行为记录在 Linux man page 中:

If oldpath and newpath are existing hard links referring to the same file, then rename() does nothing, and returns a success status.

这也在 POSIX 中指定:

If the old argument and the new argument resolve to the same existing file, rename() shall return successfully and perform no other action.

关于python - 静默 os.rename 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31682433/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com