完整代码
# -*- 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