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?