File not found/Windows file error with Windows path
- windows
- path
The user usually has something like this:
with open('C:\SomePath\spam.txt') as f:
contents1 = f.read()
with open('C:\SomePath\beans.txt') as f:
contents2 = f.read()
The first one works. The second one raises a FileNotFoundError
. Or maybe they’re passing a path like that to subprocess
, and instead they get The filename, directory name, or volume label syntax is incorrect.
from the shell.
The problem is that \b
doesn’t mean a backslash and a b, it means backspace. \S
and \s
happen to not be defined escape characters the way \b
is, so the first one happens to work by luck.
The fix is to use raw strings, escape the backslashes, or use forward slashes.