How do I raise a FileNotFoundError properly?

后端 未结 1 1397
耶瑟儿~
耶瑟儿~ 2021-02-01 12:33

I use a third-party library that\'s fine but does not handle inexistant files the way I would like. When giving it a non-existant file, instead of raising the good old

1条回答
  •  醉梦人生
    2021-02-01 12:50

    Pass in arguments:

    import errno
    import os
    
    raise FileNotFoundError(
        errno.ENOENT, os.strerror(errno.ENOENT), filename)
    

    FileNotFoundError is a subclass of OSError, which takes several arguments. The first is an error code from the errno module (file not found is always errno.ENOENT), the second the error message (use os.strerror() to obtain this), and pass in the filename as the 3rd.

    The final string representation used in a traceback is built from those arguments:

    >>> print(FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), 'foobar'))
    [Errno 2] No such file or directory: 'foobar'
    

    0 讨论(0)
提交回复
热议问题