And I'd like to specifically achieve that with the try catch construct.
This related question suggests that I can do:
try:
open(fileName, 'wb+')
except:
print("File already opened!")
raise
However, it doesn't work me. I can open the same file multiple times without any problem:
fileObj1 = open(fileName, 'wb+')
fileObj2 = open(fileName, 'wb+')
Is it because I have Python 3.5? Or because I'm using Raspbian?
Thanks for the help!
You should open the same file but assign them to different variables, like so:
file_obj = open(filename, "wb+")
if not file_obj.closed:
print("File is already opened")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With