How to check whether a file is_open and the open_status in python

This is not quite what you want, since it just tests whether a given file is write-able. But in case it's helpful:

import os

filename = "a.txt"
if not os.access(filename, os.W_OK):
    print "Write access not permitted on %s" % filename

(I'm not aware of any platform-independent way to do what you ask)


Here is an is_open solution for windows using ctypes:

from ctypes import cdll

_sopen = cdll.msvcrt._sopen
_close = cdll.msvcrt._close
_SH_DENYRW = 0x10

def is_open(filename):
    if not os.access(filename, os.F_OK):
        return False # file doesn't exist
    h = _sopen(filename, 0, _SH_DENYRW, 0)
    if h == 3:
        _close(h)
        return False # file is not opened by anyone else
    return True # file is already open

Tags:

Python