Python escape character

2019-04-09 03:24发布

问题:

I've struggled for hours with this and although I found a solution, I don't like it. Is there a built in way to solve this:

You are on Windows with a variable containing a path. You are trying to open a file with it, but it contains escape characters that you can't determine until runtime.

If you use 'shutil' and do: shutil.copy(file_path, new_file_path)

It works fine.

But if you try and use the same path with:

f = open(file_path, encoding="utf8")

It doesn't work because the '\a' in the path is read as a 'Bell' = 7

I tried doing all of these, but the only thing I've gotten to work is the custom function 'reconstruct_broken_string'.

    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 printout:

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 rather than this function? Why does it work with 'shutil' and not 'open'

Thanks

回答1:

Your problem is on this line:

file_path = "F:\ScriptsFilePath\addons\import_test.py"

Try one of these:

file_path = r"F:\ScriptsFilePath\addons\import_test.py"
file_path = "F:\\ScriptsFilePath\\addons\\import_test.py"

Or even:

file_path = "F:/ScriptsFilePath/addons/import_test.py"

(Yes, Windows accept forward slash as a file separator.)

Ref: http://docs.python.org/2/reference/lexical_analysis.html#string-literals



回答2:

Here is a simplified version demonstrating how 'repr' doesn't work correctly.

file_path = "F:\tab\a_bell\newline.py"
print(file_path)
print(repr(file_path))

This prints:

F:  ab_bell
ewline.py

and

F:\tab\x07_bell\newline.py'

As you can see 'repr' works with escape-tab, escape-newline, etc., but it doesn't work with '\a' which is escape bell.

Is this is bug in 'repr'? Is there a built in solution to this problem that doesn't require programmers to write a custom function like the 'reconstruct_broken_string(s)'? If not, how can python be this lame?



回答3:

If the path is in a variable, just replace all '\' with '/' using any of Python's string manipulation functions. It should solve the problem.



回答4:

I have experienced same exact problem - tried path = 'C:\temp\importfile.xlsx' and kept getting an error "No such file or directory: 'C:\Temp\importdata.xlsx'". I used forward slashes instead and my import worked. Have you tried file_path = "F:/ScriptsFilePath/addons/import_test.py"?



回答5:

You can use an r in front of a string so that Python handles it as a raw string-

filePath = input()
try:
    print(filePath)
except:
    print(r""+filePath)