我的目标是要知道一个文件是否被其他进程锁定,即使我没有访问该文件的权限!
更清楚地说,假设我使用Python内置的open()
函数打开文件,并带有 'wb'
参数(用于写入)。如果:
- 用户没有文件的访问权限或者
- 文件被其他进程锁定,那么
open()
将会引发IOError
,并且errno 13 (EACCES)
那么如何在这里检测情况(2)呢?
(我的目标平台是Windows)
我的目标是要知道一个文件是否被其他进程锁定,即使我没有访问该文件的权限!
更清楚地说,假设我使用Python内置的open()
函数打开文件,并带有 'wb'
参数(用于写入)。如果:
open()
将会引发 IOError
,并且errno 13 (EACCES)
那么如何在这里检测情况(2)呢?
(我的目标平台是Windows)
您可以使用os.access
来检查访问权限。如果访问权限良好,则必须是第二种情况。
正如之前的评论建议的一样,os.access
不能返回正确的结果。
但我在网上找到了另外一段代码,可以实现这个功能。关键是它尝试重命名文件。
来自:https://blogs.blumetech.com/blumetechs-tech-blog/2011/05/python-file-locking-in-windows.html
def isFileLocked(filePath):
'''
Checks to see if a file is locked. Performs three checks
1. Checks if the file even exists
2. Attempts to open the file for reading. This will determine if the file has a write lock.
Write locks occur when the file is being edited or copied to, e.g. a file copy destination
3. Attempts to rename the file. If this fails the file is open by some other process for reading. The
file can be read, but not written to or deleted.
@param filePath:
'''
if not (os.path.exists(filePath)):
return False
try:
f = open(filePath, 'r')
f.close()
except IOError:
return True
lockFile = filePath + ".lckchk"
if (os.path.exists(lockFile)):
os.remove(lockFile)
try:
os.rename(filePath, lockFile)
sleep(1)
os.rename(lockFile, filePath)
return False
except WindowsError:
return True
~$excelfilename.xlsx
的隐藏文件。 - Meredith Hesketh Fortescue根据文档:
errno.EACCES
Permission denied
errno.EBUSY
Device or resource busy
try:
fp = open("file")
except IOError as e:
print e.errno
print e
fp = open("file")
之后使用 fp.close()
,我认为会更安全。 - Yuda Prawira