+ -
当前位置:首页 → 问答吧 → Python 读写文件

Python 读写文件

时间:2010-10-20

来源:互联网

想要打开一个文件,既要读,也要写,就是先把文件内容读出来,然后往文件里写东西。

Python code

fileObj = open("test.ini","r+")
content = fileObj.read()
print content
fileObj.write("what's up")
fileObj.close()


这样写。。。居然报错:
test
Traceback (most recent call last):
File "D:\Proj\PythonProj\test.py", line 7, in <module>
fileObj.write("what's up")
IOError: [Errno 0] Error

作者: mid__night   发布时间: 2010-10-20

肯定报错的,你以读的方式打开,然后用这对象去写是不行的。
你要以写的方式打开再操作

Python code

fileObj_r = open("test.ini","r+")
content = fileObj_r.read()
fileObj_r.close()
print content
fileObj_w = open("test.ini","w+")
fileObj_w.write("what's up")
fileObj_w.close()

#或者这样:
content = open("test.ini","r+").read()
print content
fileObj_w = open("test.ini","w+")
fileObj_w.write("what's up")
fileObj_w.close()




写只能用写方式打开的对象

作者: amu9900   发布时间: 2010-10-20