如何检查文件是否被R / W锁定

时间:2016-03-02 15:42:20

标签: python file-io unicode msvcrt

我已经查看了Python : Check file is lockedHow to check whether a file is_open and the open_status in python。 通常,以下代码适合我的需要,但它在Python 2中不适用于Unicode字符串。

from ctypes import cdll

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

def is_open(filename):
    h = _sopen(filename, 0, _SH_DENYRW, 0)
    try:
     return h == -1
    finally:
        _close(h)

有什么建议我应该做什么?

1 个答案:

答案 0 :(得分:1)

问题解决了! 只需添加两行:

from ctypes import cdll

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

def is_open(filename):
    func = _wsopen if type(filename) is unicode else _sopen
    h = func(filename, 0, _SH_DENYRW, 0)
    try:
     return h == -1
    finally:
        _close(h)