如何处理OSError:[Errno 36]文件名太长

Max*_*tti 2 python filenames long-filenames python-3.x

在处理尝试创建现有文件或尝试使用不存在的文件时发生的错误时OSError,抛出的s具有子类(FileExistsError,FileNotFoundError).当文件名太长时,我找不到特殊情况的子类.

确切的错误消息是:

OSError: [Errno 36] File name too long: 'filename'
Run Code Online (Sandbox Code Playgroud)

我想捕获文件名太长时发生的OSError,但仅当文件名太长时才会发生.我希望赶上其他OSError可能发生的秒.有没有办法实现这个目标?

编辑:我知道我可以检查文件名长度,但最大文件名长度变化太大,具体取决于操作系统和文件系统,我没有看到这样的"干净"解决方案.

Łuk*_*ski 6

只需检查errno捕获的异常的属性.

try:
    do_something()
except OSError as exc:
    if exc.errno == 36:
        handle_filename_too_long()
    else:
        raise  # re-raise previously caught exception
Run Code Online (Sandbox Code Playgroud)

为了便于阅读,您可以考虑使用errno内置模块中的适当常量而不是硬编码常量.


pst*_*tix 5

您可以指定您希望如何捕获特定错误,例如errno.ENAMETOOLONG

具体到你的问题...

try:
    # try stuff
except OSError as oserr:
    if oserr.errno != errno.ENAMETOOLONG:
        # ignore
    else:
        # caught...now what?
Run Code Online (Sandbox Code Playgroud)

具体到你的评论...

try:
    # try stuff
except Exception as err:
    # get the name attribute from the exception class
    errname = type(err).__name__
    # get the errno attribute from the exception class
    errnum = err.errno
    if (errname == 'OSError') and (errnum == errno.ENAMETOOLONG):
        # handle specific to OSError [Errno 36]
    else if (errname == 'ExceptionNameHere' and ...:
        # handle specific to blah blah blah
    .
    .
    .
    else:
        raise # if you want to re-raise; otherwise code your ignore
Run Code Online (Sandbox Code Playgroud)

这将抓取由try. 然后它检查是否__name__匹配任何特定的异常以及您要指定的任何其他条件。

您应该知道except如果遇到错误,除非您指定一个具体的异常,否则无法绕过。