Python Forum

Full Version: Reading and writing Windows filepath without treating backslash as escape character
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am writing a python script to sit between two Windows applications, one that generates a list of filenames, including the full path, and the other that requires a list of filenames, including the full path. How do I read from and write to text files that use vanilla Windows path names?

Thanks
r in front of a string makes it interpret as a raw string
r'C:\User\UserName\'
or you can just escape it by doing
'C:\\User\\UserName\\'
But if I am reading from a file that only has single backslashes, how do I read the text as raw?
When you get the path (bytes) from a file, the string is read as it is. There is no need to escape something which comes from outside. The representation of a string literal in program code is a different thing. In this case Python is interpreting the text. It allows shorthands like \0 \n \t for special characters or \x43 for hexadecimal.