2017-01-01 49 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