2017-01-01 114 views
-1

open()在python中創建文件?如果沒有,是否有一個功能可以做到這一點?當我使用這個,它給我Python中的文件創建功能

"IOError: [Errno 2] No such file or directory: '/home/sanjiv/Desktop/COSURP/pyfiles/f1.txt'"

我不應該把位置創建文件?如果沒有,哪裏來創建它

f = open('/home/sanjiv/Desktop/COSURP/pyfiles/f1.txt', 'r+') 
gpa = {'fall15':4.0, 'spr16':3.47, 'fall16':4.0} 
for s in gpa: 
    f.write(str(s) + '\n') 
f.close() 
+0

是否該目錄已存在? –

回答

1

如果你要打開的文件寫,你應該使用w爲(在open功能)的第二個參數,而不是r+

w將打開文件寫(和截斷的文件,如果它已經存在):

f = open('/home/sanjiv/Desktop/COSURP/pyfiles/f1.txt', 'w') 
gpa = {'fall15':4.0, 'spr16':3.47, 'fall16':4.0} 
for s in gpa: 
    f.write(str(s) + '\n') 
f.close() 

Note that if you want to open a file in the directory /home/sanjiv/Desktop/COSURP/pyfiles/ this directory must exists and you must have write-permissions to this directory.

+0

該文件最初不存在。這工作!謝謝! – Sanjiv