import os
if os.access(filepath, os.W_OK):
print("Can write file - and remove it, too")
else:
print("Cannot write file")
从医生那里
os.F_OK, os.R_OK, os.W_OK, os.X_OK [are] values to pass as the mode parameter of access() to test the existence, readability, writability and executability of path, respectively.
def is_file_deletable(file_path):
''' return True if file is deletable, False otherwise '''
file_dirname = os.path.dirname(file_path) # get the directory name of file_path
if os.path.isfile(file_path): # if file_path exists and is a file
if os.access(file_path, os.W_OK): # if file_path has write permission
if os.access(file_dirname, os.W_OK | os.X_OK): # if directory containing file_path has write and execute premisions
try: # if file_path can be opened for write
file = open(file_path, 'w')
file.close()
return True # file_path is not locked
except OSError: # if file_path can't be opened for write
pass # file_path is locked
return False
短版
def is_file_deletable(file_path):
file_dirname = os.path.dirname(file_path) # get the directory name of file_path
if os.access(file_dirname, os.W_OK | os.X_OK): # if folder containing file_path has write and execute permission
try: # if file_path can be opened for write
file = open(file_path, 'w')
file.close()
return True # file_path is a file and has write permission and is not locked
except OSError: # if file_path can't be opened for write
pass # file_path is not a file, or don't has write permission or is locked
return False
您可以使用^{} 执行此操作
从医生那里
解释
要检查文件是否可删除,我必须检查
file_path
是否具有写入权限这还不够。删除文件还需要对包含该文件的目录具有写入和执行权限。因此,我必须检查包含该文件的目录是否具有写入和执行预任务
这还不够。文件可以被其他进程锁定,因此我必须检查是否可以访问该文件
我还可以检查
file_path
是否是一个文件解决方案
短版
相关问题 更多 >
编程相关推荐