当前位置:首页 >> 脚本专栏

如何通过python检查文件是否被占用

一、思路

1、通过window的aip函数CreateFile()函数获得文件句柄

2、检测在获得句柄的时候是否报错“文件被占用无法打开”

3、如果没有报错返回文件句柄,说明文件没有被占用;如果报错说明文件被占用

二、需import

import win32filefrom ctypes import windll 两个库

三、代码

#-*- coding: utf-8 -*-
from ctypes import windll
import time
import win32file
from win32file import *
 
def is_open(filename):
 
  try:
    #首先获得句柄
    vHandle =win32file.CreateFile(filename, GENERIC_READ, 0, None, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, None)
    #判断句柄是否等于INVALID_HANDLE_VALUE
    if int(vHandle)==INVALID_HANDLE_VALUE:
      print("# file is already open")
      return True # file is already open
    win32file.CloseHandle(vHandle)
 
  except Exception as e:
    print(e)
    return True

该代码说白了就是将C++的写法按python写法来写的,网上的其他写法通过os包来做的我发现失败了。