Reputation: 549
I want to do some changes in one file. For this purpose I am doing a temporary file where I write content with all wanted changes and at the end I try to replace the original file with this temp one.
Temp file is created and it looks like I expected, but replacing operation do not work.
This is my code which fails:
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)
but this gives me an error:
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process
Is my usage of 'replace' function is wrong?
Upvotes: 1
Views: 1876
Reputation: 75
When you are calling replace() inside 'with' the file is still open as you are still inside the scope of 'with'.
As soon as you're out of 'with' the file has now been closed and you can now replace with os.replace().
Try it.
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)
Upvotes: 1
Reputation: 872
your command os.replace(temp.name, file_path) has to be out of the 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)
Upvotes: 1