Reputation: 3501
Yes, there are many other questions here on this topic. I have looked at the responses but I have not seen any which gives a useful solution.
I have the problem in its simplest form:
import os, time
hfile = "Positions.htm"
hf = open(hfile, "w")
hf.write(str(buf))
hf.close
time.sleep(2) # give it time to catch up
os.system(hfile) # run the html file in the default browser
I get this error message: "The process cannot access the file because it is being used by another process". The file is referenced nowhere else in the program.
No other process is using it, since I can access it without error from any other program, even if I run os.system(file)
from the python console.
There's no point in using unlocker, because as soon as I leave the program, I can open the html file in the browser with no complaints from the system.
It looks like 'close' is not properly releasing the file.
I run programs this way out of perl all the time, with no problem except requiring the 1 or 2 second delay.
I'm using Python 3.4 on Win7.
Any suggestions?
Upvotes: 0
Views: 426
Reputation: 11049
You're not calling close()
. Needs to be:
import os, time
hfile = "Positions.htm"
hf = open(hfile, "w")
hf.write(str(buf))
hf.close() # note the parens
time.sleep(2) # give it time to catch up
os.system(hfile) # run the html file in the default browser
However to avoid problems like this you should use a context manager:
import os, time
hfile = "Positions.htm"
with open(hfile, 'w') as hf:
hf.write(str(buf))
os.system(hfile) # run the html file in the default browser
The context manager will handle the closing of the file automatically.
Upvotes: 1