Python 读取文件 写入文件

来源:互联网 发布:linux shell编程实例 编辑:程序博客网 时间:2024/06/05 02:38

读取文件:

#coding=utf-8try:f=open('aa.txt')    #默认以只读的方式打开文件#word=f.read()       #一次性读取,文件较大时不适合#word=f.read(20)     #一次性读取20个字符line=f.readline()while  line!='':print(line)line=f.readline()f.close()except IOError:print("文件打开出错!!")exit()

写入文件:

#coding=utf-8try:f=open('aa.txt','w')   #r:只读,w:写(替换),a:附加(不替换),r+:读取和写入(不常用)f.write('This file is not empty!')f.close()except IOError:print("文件打开出错!!")exit()


原创粉丝点击