2017-04-27 43 views
0

所以我用這個代碼:由於「PermissionError」,Windows 7,Python 3.6.0無法創建新文件。

test_file = open('c:\\test.txt', 'w') 
test_file.write('TEST') 
test_file.close() 

而且它返回此錯誤:

PermissionError:[錯誤13]許可被拒絕: 'C:\ test.txt的'

什麼應該發生的事情是它會生成一個txt文件,在其中寫入TEST,就是這樣。

使用Google搜索錯誤未返回任何結果。 (無論如何我都能理解),我對編程等方面相當陌生,所以請給我一個簡單的答案(如果可能的話)。

+0

你試圖打開一個目錄作爲一個文件,這可能會失敗。 – Aditya

+1

您沒有權限在'c:\\'中創建一個文件。在你的用戶文件夾中創建它。 –

+0

謝謝你,克勞斯,完美的工作! – negaman

回答

0
import os 
#you don't have permission to write to the root folder in C drive. You can try to write to your desktop 
test_file = open(os.path.join(os.environ["HOMEPATH"], "Desktop","test.txt"), 'w') 
test_file.write('TEST') 
test_file.close() 
#Now check your desktop you should see the test.txt file 
+0

這應該是'home_path = os.environ [「HOMEDRIVE」] + os.environ [「HOMEPATH」]'。但是,現在使用'os.environ [「USERPROFILE」]'更常見。你可以通過'os.path.expanduser('〜\\ Dekstop')'直接得到這個。在任何情況下,這都假定用戶的「桌面」文件夾尚未完全重定位到其他目錄或其他驅動器。大多數用戶已知的文件夾可以使用文件夾屬性對話框輕鬆移動。 – eryksun

相關問題