我有麻煩在我的python編譯器中將路徑分成兩行。 這只是編譯器屏幕上的一個很長的路徑,我不得不將窗口拉得太大。我知道如何將打印(「字符串」)分成兩行代碼,能夠正確編譯,而不是打開(路徑)。當我寫這篇文章時,我注意到文本框甚至無法將它全部保存在一行中。 打印()分手長路徑名
`raw_StringFile = open(r'C:\Users\Public\Documents\year 2013\testfiles\test code\rawstringfiles.txt', 'a')`
我有麻煩在我的python編譯器中將路徑分成兩行。 這只是編譯器屏幕上的一個很長的路徑,我不得不將窗口拉得太大。我知道如何將打印(「字符串」)分成兩行代碼,能夠正確編譯,而不是打開(路徑)。當我寫這篇文章時,我注意到文本框甚至無法將它全部保存在一行中。 打印()分手長路徑名
`raw_StringFile = open(r'C:\Users\Public\Documents\year 2013\testfiles\test code\rawstringfiles.txt', 'a')`
這正是\
是。
>>> mystr = "long" \
... "str"
>>> mystr
'longstr'
或者你的情況:
longStr = r"C:\Users\Public\Documents\year 2013\testfiles" \
r"\testcode\rawstringfiles.txt"
raw_StringFile = open(longStr, 'a')
編輯
好了,你甚至都不需要\
如果你使用括號,即:
longStr = (r"C:\Users\Public\Documents\year 2013\testfiles"
r"\testcode\rawstringfiles.txt")
raw_StringFile = open(longStr, 'a')
在行尾使用\不是PEP8ish – cmd
@cmd:Gah! C!它滲透和毒害一切! –
你可以將你的字符串放在括號內,如下所示:
>>> (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'
這被稱爲「字符串文字串聯」。從docs引用:
多個相鄰的字符串(由空格分隔),使用不同的引用慣例可能 ,是允許的,並且它們的意義是 與它們的串聯。因此,「你好」「世界」相當於「helloworld」 。此功能可用於減少所需的 反斜線數量,拆分長串方便地跨長 線,甚至將註釋添加到字符串的部分,例如:
re.compile("[A-Za-z_]" # letter or underscore "[A-Za-z0-9_]*" # letter, digit or underscore )
另見:
的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')
您不能使用反斜槓作爲原始字符串文字中的最後一個字符。 –
Python有所謂Implicit line joining一個漂亮的功能。
圓括號,方括號或花括號中的表達式可以在不使用反斜槓的情況下分割爲多條物理線。例如:
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。
我只是有這個非常問題在Python 3.5在Windows 7和這工作:
imgPath = ("D:\EclipseNEON\EclipseWorkspaces\EclipsePythonWorkspace"
"\PythonLessons\IntroducingPython\GUIs\OReillyTarsierLogo.png")
關鍵的一點是,至少在Windows中,在給定的子字符串中的最後一個字符不能是一個反斜槓(「\」)字符。
這裏的長路徑名非常有用的提示。我認爲在多行上使用r前綴有很大幫助。 – Adreamer82