检查文件是否可删除

2024-05-16 15:13:42 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在python中检查文件是否可删除而不删除它?毕竟,我将删除它与:

try:
    os.remove(file_path)
except OSError as error:
    print(error)

所以检查和删除之间没有安全漏洞的问题。我只需要在按下按钮之前通知用户出了问题


Tags: 文件path用户osaserror按钮remove
2条回答

您可以使用^{}执行此操作

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.

解释

要检查文件是否可删除,我必须检查file_path是否具有写入权限

os.access(file_path, os.W_OK)

这还不够。删除文件还需要对包含该文件的目录具有写入和执行权限。因此,我必须检查包含该文件的目录是否具有写入和执行预任务

os.access(file_dirname, os.W_OK | os.X_OK)

这还不够。文件可以被其他进程锁定,因此我必须检查是否可以访问该文件

try:
    file = open(file_path, 'w')
    file.close()
except OSError:
    print('File locked')

我还可以检查file_path是否是一个文件

os.path.isfile(file_path)

解决方案

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

相关问题 更多 >