Python Example Method of Using access to Judge Whether File Is Occupied
- 2021-08-28 20:45:42
- OfStack
Some small partners want to know whether access () function can judge that a file is occupied? In theory, it doesn't work. access () returns the read and write attributes of the file. In order to convince my friends, this site has been tested simply.
>>> import os
>>> fn = r'D:\temp\csdn\t.py' # Files for testing
>>> os.access(fn, os.F_OK) # Does the file exist
True
>>> os.access(fn, os.R_OK) # Is the file readable
True
>>> os.access(fn, os.W_OK) # Whether the file is writable
True
>>> os.access(fn, os.X_OK) # Is the file executable
True
>>> fp = open(fn, 'a+') # Open the file as appended write
>>> os.access(fn, os.F_OK) # Of course the file is still there
True
>>> os.access(fn, os.R_OK) # The file is still readable
True
>>> os.access(fn, os.W_OK) # The file is still writable
True
>>> os.access(fn, os.X_OK) # The file is still executing
True
>>> fp.close()
It can be seen that os. access () returns the file read and write attributes, which has nothing to do with whether the file is occupied or not.
Later, some students in the group suggested that we might as well try open file with try. If it is successful, it means that the file is not occupied, and if an exception is thrown, it means that the file is occupied. Is this really the case? Let's use code to verify 1.
>>> fp1 = open(fn, 'a+')
>>> fp2 = open(fn, 'a+')
>>> fp1.close()
>>> fp2.close()
The results show that the system does not throw an exception when the same file is opened several times by writing. Why is this happening? The reason is that open files and occupied files are completely different problems. By the way, when doing the above test, don't use 'w', otherwise the contents of the file will be emptied.
So, how should Python be used to judge whether a file is occupied? This problem still needs to be solved at the operating system level, that is, relying on win32api module.
>>> import win32file
>>> def is_used(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
>>> fn = r'D:\temp\csdn\t.py'
>>> is_used(fn)
False
>>> fp = open(fn, 'a+')
>>> is_used(fn)
True
>>> fp.close()
>>> is_used(fn)
False
It is simply verified that the function is_used () is basically available under 1.