[Tutor] Delete file before function ends

Tim Golden mail at timgolden.me.uk
Mon Oct 6 18:15:28 CEST 2008


Adrian Greyling wrote:
> Not sure if this is possible, but I'll ask anyway.  Below is a code snippet
> that creates my "problem"...  What I'd like to do, is create a plain text
> file, use the associated program to open said textfile, (using os.startfile)
> and after the associated program has what it needs to open the file and then
> of course, has the current focus, I'd like to delete the text file in the
> background, so to speak.  (Please assume that the program doesn't lock
> 'mytextfile.xyz' when it opens it.)
> 
> What happens with the code snippet below, is that it doesn't really start
> the second program until the function is finished.  I tried using
> time.sleep() in between the os.startfile() and os.remove(), but it just
> delays opening 'mytextfile.xyz' and actually deletes the file before my
> second program can open it up.  Any way around this??
> 
> path = "c:\MyFolder\mytextfile.xyz"
> #bunch of stuff here to create 'mytextfile.xyz"
> os.startfile(path)
> os.remove(path)


Strange. I would have expected the opposite effect: the
os.startfile runs (notepad, or whatever) but doesn't
return control until it's complete.

In any case, try the following snippet. The sleep is
needed because the app probably won't launch in time
to get there before the remove does.

<code>
import os
import subprocess
import time

FILENAME = os.path.abspath ("temp.txt")
f = open (FILENAME, "w")
f.write ("blah blah")
f.close ()

subprocess.Popen ([FILENAME], shell=True)
time.sleep (1.0)
os.remove (FILENAME)

</code>

TJG


More information about the Tutor mailing list