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

前端 未结 4 534
暗喜
暗喜 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
    
    0 讨论(0)
  • 2021-01-12 08:18

    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)

    0 讨论(0)
  • 2021-01-12 08:19

    I think the best way to do that is to try.

    def is_already_opened_in_write_mode(filename)
         if os.path.exists(filename):
             try:
                 f = open(filename, 'a')
                 f.close()
             except IOError:
                 return True
         return False
    
    0 讨论(0)
  • 2021-01-12 08:24

    I don't think there is an easy way to do what you want, but a start could be to redefine open() and add your own managing code. That said, why do you want to do that?

    0 讨论(0)
提交回复
热议问题