<div dir="ltr"><br><div class="gmail_extra"><br><div class="gmail_quote">On Sat, Mar 26, 2016 at 7:21 PM, Glynn Clements <span dir="ltr"><<a href="mailto:glynn@gclements.plus.com" target="_blank">glynn@gclements.plus.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><span class=""><br>
Paulo van Breugel wrote:<br>
<br>
> > In the addon r.forestfrag (python script), I used os.remove() to<br>
> > remove some temporary files (in lines 230, 258 and 430). However, this<br>
> > fails in Windows, with an error message like below:<br>
> ><br>
> > WindowsError: [Error 32] The process cannot access the file because it<br>
> > is being used by another process:<br>
> > 'c:\\users\\uqdshana\\appdata\\local\\temp\\tmpwlv54l'<br>
> ><br>
> > Removing these lines with os.remove() solves the problem, but than the<br>
> > user is left with these temporary files. Is there a Window compatible<br>
> > way to remove them in the script?<br>
><br>
> Perhaps I should have looked harder first, the underlying problem<br>
> (described here: <a href="https://www.logilab.org/blogentry/17873" rel="noreferrer" target="_blank">https://www.logilab.org/blogentry/17873</a>) seems to be<br>
> that the file needs to be closed at OS level, which can be done using<br>
> os.close().<br>
<br>
</span>Ideally, files should be handled using context managers and "with".<br>
<br>
Python's own file objects are already context managers, so you can use<br>
e.g.<br>
<br>
with open(filename) as f:<br>
data = f.read()<br>
# by this point, f has already been closed<br>
<br>
For dealing with OS-level descriptors, you can use contextlib (Python<br>
2.5+) to easily create context managers, e.g.<br>
<br>
import os<br>
import tempfile<br>
from contextlib import contextmanager<br>
<br>
@contextmanager<br>
def temp():<br>
fd, filename = tempfile.mkstemp()<br>
try:<br>
yield (fd, filename)<br>
finally:<br>
os.close(fd)<br>
os.remove(filename)<br>
<br>
if __name__ == '__main__': ...<br>
with temp() as (fd, filename):<br>
whatever()<br>
# fd has been closed and the file removed<br>
<br>
Use of "with" ensures that clean-up happens in the event of an<br>
exception or other forms of early exit (e.g. return, break, continue).<br></blockquote><div><br></div><div>Thanks Glynn.. very helpful (but I have to admit that I will need to study this more carefully to get to understand it all).<br> <br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<span class="HOEnZb"><font color="#888888"><br>
--<br>
Glynn Clements <<a href="mailto:glynn@gclements.plus.com">glynn@gclements.plus.com</a>><br>
</font></span></blockquote></div><br></div></div>