gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:52:32 25 4
gpt4 key购买 nike

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

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

这是我失败的代码:

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

我对“替换”功能的使用是否错误?

最佳答案

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

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)

关于python - 尝试用创建的临时文件替换原始文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50569253/

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