1.python内置函数open()学习经验分享

♀尐吖头ヾ 提交于 2019-12-06 14:56:53



一、来源

python官网(https://www.python.org/)→Docs→Docs for other versions→Python 2.7(stable)→Library Reference→Built in Functions.

或者

把PDF文档直接下载到本地:python官网(https://www.python.org/)→Docs→Docs for other versions→Python 2.7(stable)→Download→Download these documents


二、以open()函数为例

python官网(https://www.python.org/)→Docs→Docs for other versions→Python 2.7(stable)→open()
语法:open(name[,mode[,buffering]])
name是必须的,模式和缓冲参数是可选的。模式包括:'r'只读模式,'w'写模式,'a'追加模式,'b'二进制模式,'+'读/写模式
'r'只读模式
# -*- coding: utf-8 -*-     
#open()函数测试
f= open('F:/test/py/resource/test1.txt','r')
print f.read()
f.close()
注:test1.txt中只有一行数字1 2 3
结果显示:1 2 3

‘w’写模式
# -*- coding: utf-8 -*-     
#open()函数测试
f= open('F:/test/py/resource/test1.txt','w')
f.write('4 5 6')
f.close()
f= open('F:/test/py/resource/test1.txt','r')
print f.read()
f.close()
注:'w'模式会把之前的数据擦除掉,重新写入。

‘a’追加模式
# -*- coding: utf-8 -*-     
#open()函数测试
f= open('F:/test/py/resource/test1.txt','w')
f.write('4 5 6')
f.close()
f= open('F:/test/py/resource/test1.txt','a')
f.write('\n3333')
f.close()
f= open('F:/test/py/resource/test1.txt','r')
print f.read()
f.close()
注:先在txt文档中写入包含三个数4 5 6,然后在下一行追加3333数字,打印。

备注:刚开始写python代码,很多不优雅的地方,望批评指正。



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!