How to handle OSError: [Errno 36] File name too long

Max Matti picture Max Matti · Jun 12, 2017 · Viewed 25.8k times · Source

When handling the errors that occur when trying to create an existing file or trying to use a file that doesn't exist the OSErrors that get thrown have a subclass (FileExistsError, FileNotFoundError). I couldn't find that subclass for the special case when the filename is too long.

The exact error message is:

OSError: [Errno 36] File name too long: 'filename'

I would like to catch the OSError that occurs when the filename is too long, but only when the filename is too long. I do not want to catch other OSErrors that might occur. Is there a way to achieve this?

Edit: I know that I could check the filename against a length but the maximum filename length varies too much depending on the OS and the filesystem and I don't see a "clean" solution that way.

Answer

Łukasz Rogalski picture Łukasz Rogalski · Jun 12, 2017

Simply check errno attribute of caught exception.

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

For readability you may consider using appropriate constant from errno built-in module instead of hardcoded constant.