Python 使用 try 和 except 关键字来返回目录错误

huangapple go评论62阅读模式
英文:

Python using the try and except keywords for returning directory errors

问题

In the Python code below, I created a function and pass a parameter called the dir which stands for the directory. After that, I used the try and except statements, when the function runs the try statement should open the directory passed as an argument, and if there is an error it should go to the except statement and run it.

So my issue starts at the except statement. In the except statement, I defined a variable to find the error and there is three condition to output the error that has been occurred.

But when I run this code, I get an error like: FileNotFoundError: [Errno 2] No such file or directory: '/etc/passwd', 'w' I was wondering if someone could help me solve the error so my code run perfectly.

英文:

In the Python code below, I created a function and pass a parameter called the dir which stands for the directory. After that, I used the try and except statements, when the function runs the try statement should open the directory passed as an argument, and if there is an error it should go to the except statement and run it.

So my issue starts at the except statement. In the except statement, I defined a variable to find the error and there is three condition to output the error that has been occurred.

But when I run this code, I get an error like: FileNotFoundError: [Errno 2] No such file or directory: "'/etc/passwd', 'w'" I was wondering if someone could help me solve the error so my code run perfectly.

def open_dir(dir): #Open directory
        try: #Try if the directory has no errors.
            return open(dir)
        except: #except return the error occurred.
            directory = open(dir)
            if directory == FileNotFoundError:
                return "[Errno 2] No such file or directory: 'directory'"
            elif directory == PermissionError:
                 return "[Errno 13] Permission denied: '/et3]c/passwd'"
            elif directory == IsADirectoryError:
                 return "[E'/home'rrno 21] Is a directory: '/home'"

print(open_dir("doc.docx"))
print(open_dir("'/etc/passwd', 'w'"))
print(open_dir('/home'))

答案1

得分: 1

Here is the translated code:

def open_dir(dir): # 打开目录
    try: # 尝试打开目录,检查是否出现错误。
        return open(dir)
    except FileNotFoundError: # 如果出现 FileNotFoundError 错误,则返回错误信息。
        return "[Errno 2] 文件或目录不存在: 'directory'"
    except PermissionError:
        return "[Errno 13] 权限被拒绝: '/et3]c/passwd'"
    except IsADirectoryError:
        return "[Errno 21] 这是一个目录: '/home'"

The explanation has been omitted as requested.

英文:
def open_dir(dir): #Open directory
        try: #Try if the directory has no errors.
            return open(dir)
        except FileNotFoundError: #except return the error occurred.
            return "[Errno 2] No such file or directory: 'directory'"
        except PermissionError:
            return "[Errno 13] Permission denied: '/et3]c/passwd'"
        except IsADirectoryError:
            return "[E'/home'rrno 21] Is a directory: '/home'"

This should work as you desire

The problem you have is that when you do open(dir) and it doesn't work, you go in the except fragment of your code

but in the except fragment of your code, you do open(dir), which re-throws an exception since it's the reason you are in the except statement.

When you do a try except, if somethings goes wrong in the "try", it raises an exception that you can catch in the "except" fragment, and this is where you compare the exception (with for instance except FileNotFoundError which checks if the exception is a FileNotFoundError)

答案2

得分: 0

以下是翻译好的部分:

  1. except 块应该捕获特定的异常,而不是捕获所有异常。
  2. 另一件事是,不要检查变量 directory 是否等于异常对象,而应该检查它是否是该特定异常的实例。这是因为当你使用 except 语句捕获异常时,异常对象被分配给一个变量,因此要检查变量是否是异常类的实例。
  3. 尝试这个:
def open_dir(dir):
    try:
        return open(dir)
    except FileNotFoundError as e:
        return f"[Errno 2] No such file or directory: '{e.filename}'"
    except PermissionError as e:
        return f"[Errno 13] Permission denied: '{e.filename}'"
    except IsADirectoryError as e:
        return f"[Errno 21] Is a directory: '{e.filename}'"

请注意,代码部分没有进行翻译。

英文:

The except block should catch specific exception instead of catching all exceptions. and Another thing is; instead of checking if the variable directory is equal to the exception object, you should check if it is an instance of that particular exception. This is because When you catch an exception using an except statement, the exception object is assigned to a variable so check if variable is an instance of the exception class.
Try this one:

def open_dir(dir):
    try:
        return open(dir)
    except FileNotFoundError as e:
        return f"[Errno 2] No such file or directory: '{e.filename}'"
    except PermissionError as e:
        return f"[Errno 13] Permission denied: '{e.filename}'"
    except IsADirectoryError as e:
        return f"[Errno 21] Is a directory: '{e.filename}'"

答案3

得分: 0

尝试这段代码。

def open_dir(dir, mode="r"):  # 打开目录
    try:  # 尝试检查目录是否没有错误。
        return open(dir, mode=mode)
    except Exception as e:
        if e is FileNotFoundError:
            return "[Errno 2] No such file or directory: 'directory'"
        elif e is PermissionError:
            return "[Errno 13] Permission denied: '/etc/passwd'"
        elif e is IsADirectoryError:
            return "[Errno 21] Is a directory: '/home'"

print(open_dir("doc.docx"))
print(open_dir("'/etc/passwd', 'w'"))
print(open_dir('/home'))

请注意,我已经将代码中的HTML转义字符(例如")替换为普通字符。

英文:

try this code.

def open_dir(dir, mode="r"):  # Open directory
    try:  # Try if the directory has no errors.
        return open(dir, mode=mode)
    except Exception as e:
        if e is FileNotFoundError:
            return "[Errno 2] No such file or directory: 'directory'"
        elif e is PermissionError:
            return "[Errno 13] Permission denied: '/et3]c/passwd'"
        elif e is IsADirectoryError:
            return "[E'/home'rrno 21] Is a directory: '/home'"

print(open_dir("doc.docx"))
print(open_dir("'/etc/passwd', 'w'"))
print(open_dir('/home'))

huangapple
  • 本文由 发表于 2023年5月25日 18:20:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76331224.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定