Python: file release and deletion

I’m having trouble with file close() not working as expected.

If I run this sample code:

import tempfile
import commands
import os

froot = system.tag.read("[Client]ctAppRootDirectory").value
ftemp = froot + "delete_me.txt"

ft = open(ftemp, "w+")
ft.write("File written to.")
ft.close()

try:
	os.remove(ftemp)
except:
	system.gui.messageBox("Couldn't remove " + ftemp + ".")
  • The “delete_me.txt” file is created.
  • The “Couldn’t remove delete_me.txt.” message pops up.
  • I can’t delete the file with Windows explorer. I get “File in Use” messagebox with message “The action can’t be completed because the file is open in Java™ Platform SE binary. Close the program and try again.”
  • Oddly, I can edit the file in Notepad++ and save it.
  • If I quit the Ignition! Designer I can delete the file.
  • If I run the code again it will overwrite my edit.

Any ideas what’s happening in the engine compartment?

I was able to copy/paste your code into the script console, and it works as expected after changing the file references. The file gets deleted no problem.

Where does that code get executed?

In the past I’ve had success directly using Java’s FileWriter.

The code is executed on the client’s machine.

Background: I have to do a little manipulation of recipe files on a HMI. I had considered VBA but thought, “why not see if Ignition could do it in Python?”. It can and this is the only significant trouble I’ve run into. This application shouldn’t actually need to contact the Ignition server - unless it does that in the background to check licencing.

Thanks for going to so much trouble testing the code.

Any ideas what privileges the Java clients run under? If it’s able to create and overwrite a file you would imagine it should be able to delete it too.


Update:

It works in my Script Console too! Hmm …
It works if I run it in a button too on the client.
There must be an error in my (more complex) original code that’s causing the routine to fault. I’ll check.

1 Like

You could try this, it might help manage the file itself better. I love the with statement.

from __future__ import with_statement
import os

froot = system.util.getProperty("user.home")
ftemp = froot + "\\delete_me.txt"

with open(ftemp, "w+") as ft:
	ft.write("File written to.")
	ft.close()

try:
	os.remove(ftemp)
except:
	system.gui.messageBox("Couldn't remove " + ftemp + ".")
2 Likes