How to check if a file is already opened (in the same process)
You open the same file but assign them to different variables. What you should do is:
fileobj=open(filename,"wb+")
if not fileobj.closed:
print("file is already opened")`
I'm writing with my phone so the styling may not be good but you will get the point. By the way the .closed
only checks if the file has been opened by the same python process.
I would suggest using something like this
# Only works on Windows
def is_open(file_name):
if os.path.exists(file_name):
try:
os.rename(file_name, file_name) #can't rename an open file so an error will be thrown
return False
except:
return True
raise NameError
Edited to fit the OP's specific issues
class FileObject(object):
def __init__(self, file_name):
self.file_name = file_name
self.__file = None
self.__locked = False
@property
def file(self):
return self.__file
@property
def locked(self):
return self.__locked
def open(self, mode, lock=True):#any testing on file should go before the if statement such as os.path.exists()
#replace mode with *args if you want to pass multiple modes
if not self.locked:
self.__locked = lock
self.__file = open(self.file_name, mode)
return self.file
else:
print 'Cannot open file because it has an exclusive lock placed on it'
return None #do whatever you want to do if the file is already open here
def close(self):
if self.file != None:
self.__file.close()
self.__file = None
self.__locked = False
def unlock(self):
if self.file != None:
self.__locked = False