Skip to main content
 首页 » 编程设计

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

2025年05月04日39java哥

我已经 checkout Python : Check file is locked和 How 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) 

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

请您参考如下方法:

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

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)