8

我无法在我的 python 编译器中将路径分成两行。这只是编译器屏幕上的一条长路径,我必须将窗口拉伸得太宽。我知道如何将 print("string") 分成两行可以正确编译的代码,但不是 open(path)。当我写这篇文章时,我注意到文本框甚至不能将它全部放在一行上。打印()

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

4 回答 4

12

这就是它的\用途。

>>> mystr = "long" \
... "str"
>>> mystr
'longstr'

或者在你的情况下:

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

编辑

好吧,你甚至不需要\if 你使用括号,即:

longStr = (r"C:\Users\Public\Documents\year 2013\testfiles"
               r"\testcode\rawstringfiles.txt")
raw_StringFile = open(longStr, 'a')
于 2013-10-01T20:13:10.953 回答
7

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'

所以像这样的东西应该对你有用。

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

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

myPath = os.path.join(r'C:\Users\Public\Documents\year 2013\testfiles',
                      r'testcode\rawstringfiles.txt')
raw_StringFile = open(myPath, 'a')
于 2013-10-01T20:13:56.327 回答
3

您可以将字符串放在括号内,如下所示:

>>> (r'C:\Users\Public\Documents'
...  r'\year 2013\testfiles\test          code'
...  r'\rawstringfiles.txt')
'C:\\Users\\Public\\Documents\\year 2013\\testfiles\\test          code\\rawstringfiles.txt'

这称为“字符串文字连接”。引用自文档

允许使用可能使用不同引用约定的多个相邻字符串文字(由空格分隔),并且它们的含义与它们的连接相同。因此,"hello" 'world' 等价于 "helloworld"。此功能可用于减少所需的反斜杠数量,方便地将长字符串拆分为长行,甚至可以为部分字符串添加注释,例如:

re.compile("[A-Za-z_]"       # letter or underscore
           "[A-Za-z0-9_]*"   # letter, digit or underscore
)

另见:

于 2013-10-01T20:13:24.777 回答
1

Python 有一个漂亮的特性,叫做隐式行连接

括号、方括号或花括号中的表达式可以在多个物理行上拆分,而无需使用反斜杠。例如:

month_names = ['Januari', 'Februari', 'Maart',      # These are the
               'April',   'Mei',      'Juni',       # Dutch names
               'Juli',    'Augustus', 'September',  # for the months
               'Oktober', 'November', 'December']   # of the year

所以对于你的问题-

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

编辑- 在这个例子中,它实际上是String literal concatenation

于 2013-10-01T20:20:01.337 回答