Escape characters in path

If you are on Windows and use the blender file browser to get the path to a file and try to use it with:


f = open(file_path, encoding="utf8")
lines = f.readlines()
f.close()

Sometimes it will work, but sometimes it will fail.
It took me awhile to figure out why because I was using ‘shutil’ and it didn’t object at all.
But, ‘open’ will not accept escape characters in the path. However, escape characters will always find their way in by accident. Look at this:

file_path = "F:	able\apple
ew.py"

There is a: ’ ', ‘\a’, and ’
’ = Tab, Bell, Newline.

That will result in a file not found error.
I posted a thread over at stack overflow, and despite the fact that many people have had this problem over the years, it never seems to get solved. How can python be so lame that ‘open’ looks for escape characters.
Check out the thread here: http://stackoverflow.com/questions/18682695/python-escape-character

I did find a way around it but it requires a custom function.

backslash_map = { '\a': r'\a', '\b': r'\b', '\f': r'\f',
                  '
': r'
', '\r': r'\r', '	': r'	', '\v': r'\v' }
def reconstruct_broken_string(s):
    for key, value in backslash_map.items():
        s = s.replace(key, value)
    return s

Example:

file_path = "F:\ScriptsFilePath\addons\import_test.py"
print(reconstruct_broken_string(file_path))

prints:

F:\ScriptsFilePath\addons\import_test.py

I’ve tried a dozen different methods, and none of them will replace escape characters properly.
Surely there must be a built in solution for such an obvious problem?

use a raw string:

file_path = r"F:	able\apple
ew.py"

(see the leading “r” in front of the string literal!)

or escape backslashes:

file_path = "F:\	able\\apple\
ew.py"

You should always use either of these techniques.

For printing to console etc., you might wanna use print(repr(your_string)) or “%r” % your_string to force proper encoding (however, it might lead to visible string encoding)

But the string is coming from the Blender file browser window.
You get it in a variable. You can’t put ‘r’ in front of a variable.

I think the problem is Blender is not giving you a raw encoded string in the variable.
So when you pass it on to ‘Open’, to open a file, it sees the escape character ‘’ and mis-reads it.
I think this is a Blender problem couple with the fact that ‘Open’ is not smart enough to ignore escape characters.
‘Shutil’ is smart enough, if you pass the same Blender derived path with, for example ‘\a’ in it, ‘Shutil’ knows it is a path and will perform whatever operation you want. Like file copy, etc.

the official obj importer does this to the file browser’s path:

print('

importing obj %r’ % filepath)

filepath = os.fsencode(filepath)

What seems to work for unescaped filepaths is:
http://docs.python.org/dev/library/shlex.html#shlex.quote

also see