Python程序判断文件是否被打开被占用

完整代码

# -*- coding: utf-8 -*-
# -*- version: python3.x -*-
import zlib
import base64
import os
import win32file as w

def is_open(filename):
    if not os.access(filename, os.F_OK):
        return False
    try:
        handle = w.CreateFile(filename, w.GENERIC_WRITE, 0,
                              None, w.OPEN_EXISTING, w.FILE_ATTRIBUTE_NORMAL, None)
        if int(handle) == w.INVALID_HANDLE_VALUE:
            return True
        w.CloseHandle(handle)
    except Exception as e:
        return True
    return False


c = '789c05c1d10a83201400d00fdac324b8177a0c83696bc5689bcb37a510b76eea83c5fafa9d8323bf43ba124ada51a793ecd5cf6595f36c84ef4d1578bd463cd31ac4b2c99a3cdc1ca03f20a40736bc0483b3ace2c716c046d53129a6385d9cb3ea89ba5898112fdf52b7d9a13cf4bb21ade0fb07e11e26b7'
def test():
    file = './test_file.txt'
    f = open(file, 'wb')
    print(f'file {file} is open : {is_open(file)}')
    f.write(base64.b64decode(zlib.decompress(bytes.fromhex(c))))
    f.close()
    print(f'file {file} is open : {is_open(file)}')


if __name__ == '__main__':
    test()

详解

检查文件是否能使用写的方式打开

使用winapi的CreateFile对文件进行操作,如果不报异常的话即可认为是可以打开的

注意如果文件不存在,则也返回True

注意如果文件不可写等其他异常,则也返回True

# -*- coding: utf-8 -*-
# -*- version: python3.x -*-
import os
import win32file as w
def is_open(filename):
    if not os.access(filename, os.F_OK):
        return False
    try:
        handle = w.CreateFile(filename, w.GENERIC_WRITE, 0,
                              None, w.OPEN_EXISTING, w.FILE_ATTRIBUTE_NORMAL, None)
        if int(handle) == w.INVALID_HANDLE_VALUE:
            return True
        w.CloseHandle(handle)
    except Exception as e:
        return True
    return False

参考文档

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值