Python 将特殊字符添加到路径字符串

Python adds special characters to path-string

我正在尝试使用 Python 2.7

中的路径

这就是我在我的主程序中尝试做的事情 class:

program = MyProgram()
program.doSomething('C:\Eclipse\workspace\MyProgram\files345678_Testing1_ABCD005_Static_2214_File12.txt')

在函数 doSomething(filePath) 中,字符串已经看起来像这样:

所以有一种特殊字符加上一些字符被完全删除。是什么导致了这个问题?

反斜杠似乎在创建一个特殊字符。在反斜杠后面放置一个额外的反斜杠(作为转义字符)应该可以解决这个问题。

program = MyProgram()
program.doSomething('C:\Eclipse\workspace\MyProgram\files\12345678_Testing1_ABCD005_Static_2214_File12.txt')

\ 是 Python 中的转义字符。 According to docs,您创建了包含 \f ASCII Formfeed (FF) 个字符的字符串。

String literals can be enclosed in matching single quotes (') or double quotes ("). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings). The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.

使用双斜杠(\ - 转义转义字符)或使用原始字符串文字 (r"some\path")。

String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and use different rules for interpreting backslash escape sequences.

这在你的情况下可能有点矫枉过正, 您可以使用 os.path.join 来构建路径。有了这个你有两个优势:

  • 它使用当前系统的分隔符构建路径(Unix '/' VS Windows '\')
  • 在 windows
  • 的情况下,您不必关心转义分隔符

如前所述,这对您的代码来说可能有点矫枉过正:

import os.path
program = MyProgram()
my_path = os.path.join('C:', 
                       'Eclipse', 
                       'workspace', 
                       'MyProgram', 
                       'files',
                       '12345678_Testing1_ABCD005_Static_2214_File12.txt')
program.doSomething(my_path)

我们可以通过将包含转义字符的路径名转换为原始字符串来转换 Windows 个路径名。

如果你想硬编码你的字符串,那么你可以使用

mypath = r'C:\this_is_my_path'

和python将忽略上面字符串中的'\t'。

但是,如果您有一个包含转义字符的字符串变量,那么您可以使用下面提到的方法。

def string2RawString(string):
    rawString = ''
    for i in string.split('\'):
        rawString = rawString+("%r"%i).strip("'")+"\"
    return rawString

在文件路径前使用 r

program.doSomething(r'C:\Eclipse\workspace\MyProgram\files345678_Testing1_ABCD005_Static_2214_File12.txt')