Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

path - Python escape character

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:ScriptsFilePathaddonsimport_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', '': r'', 'f': r'f',
                  '
': 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

Here is the printout:

utf-8

F:\ScriptsFilePathddons\import_test.py
'F:\ScriptsFilePathx07ddons\import_test.py'
r"'F:ScriptsFilePathddonsimport_test.py'
b'F:\\ScriptsFilePath\x07ddons\\import_test.py'
F:ScriptsFilePathddonsimport_test.py
'F:\ScriptsFilePathx07ddons\import_test.py'

F:ScriptsFilePathaddonsimport_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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your problem is on this line:

file_path = "F:ScriptsFilePathaddonsimport_test.py"

Try one of these:

file_path = r"F:ScriptsFilePathaddonsimport_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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...