How to check if a file is open (in the same process)

And I would like to specifically achieve this with the catch catch construct.

This related question suggests what I can do:

try: open(fileName, 'wb+') except: print("File already opened!") raise 

However, this does not work. I can open the same file several times without problems:

 fileObj1 = open(fileName, 'wb+') fileObj2 = open(fileName, 'wb+') 

Is it because I have Python 3.5? Or because I use Raspbian ?

Thanks for the help!

+6
source share
2 answers

You open the same file, but assign them to different variables. What you need to do:

 fileobj=open(filename,"wb+") if not fileobj.closed: print("file is already opened")` 

I write with my phone so that the style is not good, but you will understand the essence. By the way, .closed only checks if the file was opened by the same python process.

+4
source

I would suggest using something like this.

 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 meet specific OP 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 
+2
source

All Articles