I struggled with this for many hours, and although I found a solution, I do not like it. Is there a built-in way to solve this problem:
You are on Windows with a variable containing the path. You are trying to open a file with it, but it contains escape characters that you cannot determine before execution.
If you use shutil and do: shutil.copy(file_path, new_file_path)
It works great.
But if you try to use the same path with:
f = open(file_path, encoding="utf8")
This does not work because '\ a' in the path reads as "Bell" = 7
I tried to do all of this, but the only thing I got was the "restoreruct_broken_string" custom function.
file_path = "F:\ScriptsFilePath\addons\import_test.py" print(sys.getdefaultencoding()) print() print(file_path.replace('\\', r'\\')) print( '%r' % (file_path)) print( r'r"' + "'" + file_path+ "'") print(file_path.encode('unicode-escape')) print(os.path.normpath(file_path)) print(repr(file_path)) print() print(reconstruct_broken_string(file_path)) backslash_map = { '\a': r'\a', '\b': r'\b', '\f': r'\f', '\n': r'\n', '\r': r'\r', '\t': r'\t', '\v': r'\v' } def reconstruct_broken_string(s): for key, value in backslash_map.items(): s = s.replace(key, value) return s
Here is the listing:
utf-8 F:\\ScriptsFilePathddons\\import_test.py 'F:\\ScriptsFilePath\x07ddons\\import_test.py' r"'F:\ScriptsFilePathddons\import_test.py' b'F:\\\\ScriptsFilePath\\x07ddons\\\\import_test.py' F:\ScriptsFilePathddons\import_test.py 'F:\\ScriptsFilePath\x07ddons\\import_test.py' F:\ScriptsFilePath\addons\import_test.py
Is there a built-in way to do this and not this function? Why does it work with "shutil" and not "open"
thanks