引言
如何用 Python 编写代码判断一个文件是否处于占用状态?
思路- 调用 win32 api 的 CreateFile 函数来获取文件句柄
- 判断上一步获取的文件句柄是否有效
- 若无效,则说明文件正被占用;反之,就没有占用
import win32file
def is_file_using(file_name):
try:
vHandle = win32file.CreateFile(file_name, win32file.GENERIC_READ, 0, None, win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_NORMAL, None)
return int(vHandle) == win32file.INVALID_HANDLE_VALUE
except:
return True
finally:
try:
win32file.CloseHandle(vHandle)
except:
pass
if __name__ == '__main__':
file_name = 'test.txt'
f = open(file_name, 'w')
print(is_file_using(file_name)) # True
f.close()
print(is_file_using(file_name)) # False
参考
https://blog.csdn.net/qq_39241986/article/details/112386635