Python FileNotFoundError or You have a really long file path?

python
Today I encountered an interesting bug that I think it is worth to write it down for my future self.
Author

noklam

Published

August 18, 2021

FileNotFoundError? Not so quick

screenshot

To illustrate the issue, I perpared some fake file. The script is simple, it just read a file with plain text, except that the filename is really long.

error

Unforuntately, even though the file exists, Python gives me a FileNotFoundError, how come? However long debugging, I found out that this is related to the filename that exist only on Windows.

This StackOverflow thread explain this issue.

Maximum Path Length Limitation
In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is “D:*some 256-character path string*” where “” represents the invisible terminating null character for the current system codepage. (The characters < > are used here for visual clarity and cannot be part of a valid path string.)

Solution - Registry

Updating your Registry can solve this problem.

Hello World

After applying the config, I can finally read the file. :)

Summary (TLDR version)

  • Window filesystem only allow 256 characters, beyond that you will have trouble to open the file.
  • Python will not be able to see this file and throw FileNotFoundError (I have no idea, anyone know why is that?)
  • You can update registry to enable long file path in Window to fix this issue.

(Bonus: Window actually has weird behavior for long filepath, you can try to break it with different ways.)