[Tutor] Releasing a File for Access

Tim Golden mail at timgolden.me.uk
Fri Sep 12 10:17:28 CEST 2008


Wayne Watson wrote:
> Enclosed is a segment of a program which copies a txt file, but replaces 
> the first line with a new one. The new one has a suffix of tmp. After it 
> executed the code and exited the program normally (running out of code), 
> I couldn't access the new tmp file. It was listed by Win XP, but I got a 
> "file in use" messge. Do I have to exit differently to free the tmp file 
> for inspection?

If you're using 2.5+, worth using the new with statement which
should ensure file closure, altho' there's nothing in your
code which suggests that it shouldn't close anyhow. Also,
for the purpose of your copy-except-line-1 routine, consider
that files are also iterators. Put together, this snippet --
simplified for clarity -- might help things along:

<code>
from __future__ import with_statement

with open ("c:/temp/temp0.txt") as fin:
  with open ("c:/temp/temp1.txt", "w") as fout:
    fout.write ("NEW LINE 1\n")
    fin.next ()
    fout.writelines (fin)

</code>

Just in case it helps, it is possible for virus checkers
and the like (and viruses themselves for that matter) to
monitor file creation and to lock the file in share-delete
mode. If what you have is a truly temporary file, consider
using the tempfile module or at least creating it in the
%TEMP% directory which will generally be excluded for
virus checking, I think.

TJG


More information about the Tutor mailing list