![](/img/trans.png)
[英]How do you open a notepad++ python file in windows powershell?
[英]How do you open a file on windows for python? having unexpected issues
我想從python讀取Windows上的文本文件。 我已經在Mac終端上完成了一百萬次,但是剛開始使用Windows。 首先是打開文件:
file = open("C:\users\lbryan05\documents\Training\python\Lynda\ch 2\words.txt", 'r')
,它給出語法錯誤:
SyntaxError:(unicode錯誤)“ unicodeescape”編解碼器無法解碼位置2-3中的字節:截斷的\\ uXXXX轉義
我發現\\ u發生了一些奇怪的事情,因此我嘗試在路徑前面加上r以使所有反斜杠加倍:
file = open(r"C:\users\lbryan05\documents\Training\python\Lynda\ch 2\words.txt", 'r')
因此,我得到“沒有這樣的目錄存在”。 所以我認為Windows是愚蠢的,並隱藏了文件擴展名,因此我只需要發出word.txt。 之后,我對以下錯誤感到驚訝:
PermissionError:[Errno 13]權限被拒絕:“路徑”。
,這對我為什么沒有權限,因為我當然可以訪問它就毫無意義。 我正在通過Windows Powershell(和Sublime)執行python。
如果文件不是太大,建議將文件存儲在該變量上,然后在python上進行所需的更改,然后使用“ w”參數將整個文件與編輯后的數據一起保存到文件中。
嘗試這個:
# Open file to read it, and store it in a var.
with open("C:\\users\\lbryan05\\documents\\Training\\python\\Lynda\\ch 2\\words.txt", 'r') as f:
file_content = f.read()
# Do something with that var, manipulate it like you want
file_content = file_content + "test"
# Open file to write on it, and write your manipulated var.
with open("C:\\users\\lbryan05\\documents\\Training\\python\\Lynda\\ch 2\\words.txt", 'w') as w:
w.write(file_content)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.