2014-11-01 69 views
0

當我想打開C:\(windows dir。)中的文件時,此錯誤顯示爲: PermissionError:[Errno 13] PermissionError:'C:\ h。 txt'Python:將文件寫入Windows目錄時發生PermissionError

我該怎麼辦?

我知道這個問題已被問了好幾次,但我找不到解決方案!

代碼:

f=open ('C:\\h.txt','w') 
f.write ('python') 
f.close 

回答

1

我沒有贏的機器上,但是試試這個,你可以使用這些commands 嘗試使用os.fdopen

import os 
with os.fdopen(os.open('file.txt', os.O_WRONLY | os.O_CREAT, 0600), 'w') as f: 
    f.write(...)  

UPDATE

import os 
is_accessible = os.access("C:\\temp\\python",os.F_OK) #Check if you have access, this should be a path 
if is_accessible == False: #If you don't, create the path 
    os.makedirs("C:\\temp\\python") 
os.chdir("C:\\temp\\python") # Check now if the path exist 
f = os.open("p.txt", os.O_RDWR|os.O_CREAT) #Create the file 
os.write(f, b"This is a test \n") #Try to write 
os.close(f) 
+0

我嘗試了仍然錯誤顯示! – hamedb71 2014-11-01 15:35:05

+0

@ hamedb71:嘗試強制創建路徑。檢查更新 – 2014-11-01 15:37:58

+0

感謝它的工作。但對我來說有點複雜,所以我應該研究一下。 :@ – hamedb71 2014-11-01 15:46:36

0

我不是在Windows機器上,但也許你應該嘗試和創造在目錄c這個文件:\ TEMP。

同樣,確保你沒有得到記事本等與該文件打開。

+0

我的問題打開文件管理權限是我沒有管理員權限! – hamedb71 2014-11-01 15:22:00

+0

也許你可以使用C:\ Temp作爲你的工作區域或者只是你的桌面'f = open(os.path.expanduser('〜/ Desktop/h.txt','w'))..' – sotapme 2014-11-01 15:25:03