os.path.exists(..) is considered dangerous on windows

2 Nov 2016

Let's assume we have a file with a really long path (longer than 260 characters). Let's name is c:\longpath\test.txt. Here's how os.path.exists(..) behaves:

  • os.path.exists('\\?\c:\longpath\test.txt') return true.
  • os.path.exists('c:\longpath\test.txt') return false.
  • os.path.exists('\\?\c:\longpath/test.txt') return false.
  • os.path.exists('c:\longpath/test.txt') return false.

Yes, os.path.exists(..) returns the wrong value and doesn't raise an exception. os.path.isfile(..) behaves this way too.

What the hell?

Note that os.makedir(..) and os.listdir(..) raises an exception when the given path is longer than 260 characters.