Python转义符 [英] Python escape character

查看:118
本文介绍了Python转义符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为此一直努力了几个小时,尽管我找到了解决方案,但我不喜欢它. 有内置的方法可以解决此问题吗?

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:

您在Windows上具有包含路径的变量. 您正在尝试使用该文件打开文件,但是该文件包含直到运行时才能确定的转义字符.

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.

如果您使用"shutil"并执行以下操作: shutil.copy(file_path, new_file_path)

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

它工作正常.

但是,如果您尝试将相同的路径用于:

But if you try and use the same path with:

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

它不起作用,因为路径中的'\ a'被读为'Bell'= 7

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

我尝试了所有这些操作,但是我要做的唯一一件事就是自定义函数'reconstruct_broken_string'.

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

这是打印输出:

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

是否有内置的方法来执行此操作而不是执行此功能? 为什么它与"shutil"而不是"open"一起使用

Is there a built in way to do this rather than this function? Why does it work with 'shutil' and not 'open'

谢谢

推荐答案

您的问题在此行上:

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

尝试以下方法之一:

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

甚至:

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

(是的,Windows接受正斜杠作为文件分隔符.)

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

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

这篇关于Python转义符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆