我無法打開位於目錄中的文件。無法在Windows中運行的Python中的不同目錄中打開文件
請參閱下面的代碼:
file = open("E:\Python_Scratch\test.txt","w")
,但我收到以下錯誤,而打開該文件。
E:\Python_Scratch
^
SyntaxError: invalid syntax
您可以幫我解決如何打開文件嗎?
我無法打開位於目錄中的文件。無法在Windows中運行的Python中的不同目錄中打開文件
請參閱下面的代碼:
file = open("E:\Python_Scratch\test.txt","w")
,但我收到以下錯誤,而打開該文件。
E:\Python_Scratch
^
SyntaxError: invalid syntax
您可以幫我解決如何打開文件嗎?
在Python中,字符串內的反斜槓用於提供諸如換行符(\n
)之類的命令。
所以,如果你想要寫一個反斜槓,而不是給一個命令,使用兩個反斜槓:
file = open("E:\\Python_Scratch\\test.txt","w")
可以爲有關它的更多情報諮詢Documentation。
看來你是在Windows操作系統中,嘗試這種格式
file = open(r"E:\\Python_Scratch\test.txt","w")
#raw path(string) by r before ''
#after drive name :\\ double slash, you will be fine if you use single or double slashes after next path(one dir deep) and on-wards.
忘記在上一行括號給你的錯誤在Python 2.x版本例如:
x = (
print("E:\Python_Scratch\test.txt")
輸出:
File "test.py", line 2
print("E:\Python_Scratch\test.txt")
^
SyntaxError: invalid syntax
另外,與Python字符串,單反斜槓可以被解釋爲轉義碼。在你的情況下,\t
是一個標籤:
>>> print("E:\Python_Scratch\test.txt")
E:\Python_Scratch est.txt
取而代之。使用雙反斜線來表示你想要的字符串中一個真正的反斜槓,或使用原始字符串(注意領導r
):
>>> print(r"E:\Python_Scratch\test.txt")
E:\Python_Scratch\test.txt
>>> print("E:\\Python_Scratch\\test.txt")
E:\Python_Scratch\test.txt
可以張貼整個代碼?該行沒有無效的語法 –