windows下python检查文件是否被其它文件打开.md

有时候我们需要能够判断一个文件是否正在被其它文件访问,几乎不可避免的要调用操作系统接口

from ctypes import cdll
import os

_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

print is_open("test.txt")

ref:
http://stackoverflow.com/questions/8231719/how-to-check-whether-a-file-is-open-and-the-open-status-in-python

posted @ 2016-09-12 09:09  MindProbe  阅读(6913)  评论(1编辑  收藏  举报