打破长路径名称

Adr*_*r82 4 python python-3.x

我无法在python编译器中将路径分成两行.它只是编译器屏幕上的一条长路径,我必须将窗口拉得太宽.我知道如何将打印("字符串")分成两行代码,这些代码将正确编译,但不能打开(路径).当我写这篇文章时,我注意到文本框甚至无法将它全部保存在一行上.打印()

`raw_StringFile = open(r'C:\Users\Public\Documents\year 2013\testfiles\test          code\rawstringfiles.txt', 'a')`
Run Code Online (Sandbox Code Playgroud)

Geo*_*ell 5

\是为了什么。

>>> mystr = "long" \
... "str"
>>> mystr
'longstr'
Run Code Online (Sandbox Code Playgroud)

或您的情况:

longStr = r"C:\Users\Public\Documents\year 2013\testfiles" \
           r"\testcode\rawstringfiles.txt"
raw_StringFile = open(longStr, 'a')
Run Code Online (Sandbox Code Playgroud)

编辑

好吧,\如果您使用括号,甚至不需要:

longStr = (r"C:\Users\Public\Documents\year 2013\testfiles"
               r"\testcode\rawstringfiles.txt")
raw_StringFile = open(longStr, 'a')
Run Code Online (Sandbox Code Playgroud)

  • 在行尾使用 \ 不是 PEP8ish (2认同)

ely*_*ely 5

Python允许仅通过相邻放置字符串来连接字符串:

In [67]: 'abc''def'
Out[67]: 'abcdef'

In [68]: r'abc'r'def'
Out[68]: 'abcdef'

In [69]: (r'abc'
   ....: r'def')
Out[69]: 'abcdef'
Run Code Online (Sandbox Code Playgroud)

所以这样的事情应该适合你.

raw_StringFile = open(r'C:\Users\Public\Documents\year 2013\testfiles'
                      r'\testcode\rawstringfiles.txt', 'a')
Run Code Online (Sandbox Code Playgroud)

另一种选择是使用os.path.join:

myPath = os.path.join(r'C:\Users\Public\Documents\year 2013\testfiles',
                      r'testcode\rawstringfiles.txt')
raw_StringFile = open(myPath, 'a')
Run Code Online (Sandbox Code Playgroud)

  • 您不能使用反斜杠作为原始字符串文字中的最后一个字符. (5认同)