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

前端 未结 4 538
暗喜
暗喜 2021-01-12 07:39

Is there any python functions such as:

filename = \"a.txt\"
if is_open(filename) and open_status(filename)==\'w\':
   print filename,\" is open for writing\"         


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-01-12 08:11

    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
    

提交回复
热议问题