在关闭文件之前移动文件是否安全?

时间:2019-03-23 17:04:16

标签: python

我想创建一个文件,写入该文件,然后将其移动到其他位置。在关闭文件之前,可以在with块的范围内执行移动操作吗?

from pathlib import Path
my_file = Path("some_file.txt")    
with open(my_file, "w") as outfile:
    outfile.write("some stuff\n")
    Path(outfile.name).replace(Path.home / "my_file")

还是会产生某种种族状况?

我要执行此操作的原因是,我想先写入NamedTemporaryFile来处理文件,然后用它替换原始文件,所以如果在处理过程中遇到未处理的异常,我就不会这样做最终导致文件不完整。如果要将文件移到with语句之外,则必须使用额外的一行来记住文件路径。

from pathlib import Path
from tempfile import NamedTemporaryFile

my_file = Path("aoeu.txt")

with open(my_file) as infile:
    with NamedTemporaryFile("w", delete=False) as outfile:
        for line in infile:
                outfile.write(do_some_stuff(line))
        new_filename = outfile.name
Path(new_filename).replace(my_file)

0 个答案:

没有答案
相关问题