8

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!

13
  • The reason I can open a file multiple times is because "only Windows locks files when open for writing. POSIX platforms do not.". See stackoverflow.com/questions/22617452/… for more information. Commented May 29, 2016 at 23:18
  • If you are running in the same process how would you not know if the file is open? Commented May 29, 2016 at 23:46
  • @PadraicCunningham I have a script that imports an external library/module that can open and close a file. My script needs a way to know if the file is currently open or closed. Commented May 29, 2016 at 23:56
  • So you are not actually opening the file with wb+? That means reading an writing but it will truncate the data first, you would only read from it after you have written something and seek back Commented May 29, 2016 at 23:57
  • @PadraicCunningham What do you mean? I don't actually need to open the file in my script. In my question I'm doing it because I expected that it threw an error if the file was already open, thus letting me check if the file is open or closed. Commented May 30, 2016 at 0:00

2 Answers 2

10

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.

3
  • 2
    This does not solve the OP's question? He is asking how to check if a specific file is open. f=open(f_name, mode) != f_o=open(f_name, mode) because open() returns an instance of some fileobj. Therefore fileobj.closed would always evaluate to False assuming you opened the file on the previous line? Commented May 29, 2016 at 23:12
  • Although this technique is less flexible and doesn't use the try...except construct, it isn't platform dependent and actually works. I don't know why it got downvoted. Commented May 30, 2016 at 0:30
  • @maximedupre I didn't downvote but I suspect it's b/c most people end up here b/c they're trying to figure out if a different process has the file open, which is a much more difficult problem. But as your subject line notes, it's for the "same process" so this answer is 100% correct and shouldn't be downvoted, it's just not useful for most people ;-)
    – JohnE
    Commented Jul 30, 2018 at 8:46
2

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
7
  • 1
    It doesn't work, I'm able to rename a file even if it's open. Perhaps because my OS is Raspbian? Commented May 29, 2016 at 23:50
  • Perhaps that lock is OS specific, if so then I would take a look at the Python open modes here tutorialspoint.com/python/os_open.htm and try os.O_CREAT and also os.O_EXLOCK or a combination. Let me know if this works on Raspbian. I assume it will because it is not os specific. Commented May 29, 2016 at 23:58
  • os.O_EXLOCK won't be available on a pi Commented May 30, 2016 at 0:08
  • Yeah, os.O_EXLOCK is not available on a Pi. When I try it, I get AttributeError: module 'os' has no attribute 'O_EXLOCK'. Commented May 30, 2016 at 0:18
  • 1
    then I would create and share your own file obj. Look for my updated answer. Commented May 30, 2016 at 0:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.