How to check that a file is open

I’ve been trying to find the best way to check to see if a file is open. This is what I’ve come up with so far:

import os
filepath = "\\\\c:\\TST\\MyFile.txt"
isOpen = None
file_object = None
if os.path.exists(filepath):
	try:
		print "Trying to open %s." % filepath
		buffer_size = 8
		# Opening file in append mode and read the first 8 characters.
		file_object = open(filepath, 'a', buffer_size)
		if file_object:
			print "%s is not open." % filepath
			isOpen = False
	except IOError, message:
		print "File is open (unable to open in append mode). %s." % \
			  message
		isOpen = True
	finally:
		if file_object:
			file_object.close()
			print "%s closed." % filepath
else:
	print "%s not found." % filepath
print isOpen

The code above works great when it is used on a button, but when it is implemented in the shared scripts file like this:

import os

def isOpen(filepath):
	
	isOpen = None
	file_object = None
	if os.path.exists(filepath):
		try:
			print "Trying to open %s." % filepath
			buffer_size = 8
			# Opening file in append mode and read the first 8 characters.
			file_object = open(filepath, 'a', buffer_size)
			if file_object:
				print "%s is not open." % filepath
				isOpen = False
		except IOError, message:
			print "File is open (unable to open in append mode). %s." % \
				  message
			isOpen = True
		finally:
			if file_object:
				file_object.close()
				print "%s closed." % filepath
	else:
		print "%s not found." % filepath
	return isOpen

The following error occurs:

Traceback (most recent call last):
File “event:actionPerformed”, line 26, in
File “module:shared.file”, line 13, in isOpen
File “module:shared.file”, line 13, in isOpen
TypeError: open() takes exactly 1 argument (3 given)

We are using:
Ignition 7.9.0 (b2016101208)
Windows Server 2012R2
Java 1.8.0_111-b14

Any help would be great!

Seems to work for me (in the sense that both scripts do the same thing). How are you calling the shared script?

I assume you’re trying to access a file being written to by another application. Unfortunately this is really hard to do without running into file locking and race conditions.

Yes there are nuances I agree. But my question is: Why does the same code work differently when called from the Project/Shared Scripts definition vs the code being placed on a simple button action performed event?

What you’ve described would be possible if you’ve defined a function named ‘open’ in that module. That would ‘hide’ the built-in open() function from everything else in the module.

To add to Phil - I think what’s might be happening is the Jython interpreter thinking ‘isOpen’ is equivalent to an open() call.