尝试用创建的临时文件替换原始文件

Trying to replace original file with created temp file

我想对一个文件进行一些修改。为此,我正在做一个临时文件,我在其中写入所有需要更改的内容,最后我尝试用这个临时文件替换原始文件。

临时文件已创建,看起来像我预期的那样,但替换操作不起作用。

这是我失败的代码:

with tempfile.NamedTemporaryFile(mode='w', prefix=basename, dir=dirname, delete=False) as temp, open(file_path, 'r') as f:
    for line in f:
        temp.write(line + " test")
    os.replace(temp.name, file_path)

但这给了我一个错误:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process

我对'replace'函数的使用有误吗?

你的命令os.replace(temp.name,file_path)必须不在with中。

with tempfile.NamedTemporaryFile(mode='w', prefix=basename, dir=dirname, delete=False) as temp, open(file_path, 'r') as f:
    for line in f:
        temp.write(line + " test")
os.replace(temp.name, file_path)

当您在 'with' 中调用 replace() 时,文件仍处于打开状态,因为您仍在 'with' 的范围内。

一旦您离开 'with',文件现已关闭,您现在可以用 os.replace() 替换。

试试吧。

with tempfile.NamedTemporaryFile(mode='w', prefix=basename, dir=dirname, delete=False) as temp, open(file_path, 'r') as f:
    for line in f:
        temp.write(line + " test")
os.replace(temp.name, file_path)