os.link() 与 os.rename() 与 os.replace() 用于写入原子写入文件。最好的方法是什么?

DZt*_*ron 9 python

嗨,我正在尝试编写一个原子写入函数,如下所示......

with tempfile.NamedTemporaryFile(mode= "w", dir= target_directory) as f: 
     #perform file writing operation  
     os.replace(f.name, target_file_name) 
Run Code Online (Sandbox Code Playgroud)

我正在努力找出第 3 行中最好的操作是什么。我应该使用 os.replace()、os.rename() 还是应该使用 os.link() 在临时文件和目标文件之间创建硬链接?

os.link() 使用更多内存吗?它们各自有什么好处?它们都是原子的吗?

Ant*_*ile 5

os.rename/os.replace都是使用这个函数实现的

唯一的区别是os.replace使用is_replace=1它对 posix 没有影响,但MOVEFILE_REPLACE_EXISTING在 Windows 上设置标志:

如果存在名为 lpNewFileName 的文件,则该函数会将其内容替换为 lpExistingFileName 文件的内容,前提是满足有关访问控制列表 (ACL) 的安全要求。有关详细信息,请参阅本主题的备注部分。

如果lpNewFileName或lpExistingFileName命名一个目录并且lpExistingFileName存在,则报告错误。

os.link并不真正适合这个函数,除非你能保证目标文件不存在(否则os.link会出错):

$ touch a b
$ link a b
link: cannot create link 'b' to 'a': File exists
$ python3 -c 'import os; os.link("a", "b")'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
FileExistsError: [Errno 17] File exists: 'a' -> 'b'
Run Code Online (Sandbox Code Playgroud)


Dan*_*and 0

我不确定在这种情况下你所说的“原子”是什么意思。但主要区别是:

替换和重命名很相似,但替换更具跨平台性(因此,如果您知道要使用哪个系统,我认为重命名会更好)。

os.link 将使用相同数量的磁盘空间,但您将创建一个硬链接,这可能不是您想要的。