网络编程
位置:首页>> 网络编程>> Python编程>> 如何通过python检查文件是否被占用

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

作者:storm_spirit  发布时间:2023-03-20 12:25:00 

标签: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包来做的我发现失败了。

来源:https://blog.csdn.net/storm_spirit/article/details/104204072

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com