一、以写模式打开文件
out = open("data.out","w")
参数"w"表示以写方式打开文件,这是后使用print函数可以将数据写入文件。
print("写入文件测试",file=out)
注意参数file=out,当没有这个参数时,或者file=sys.stdout时,print语句把结果输出到屏幕上。
写完文件要关闭文件,确保文件都保存到磁盘上。
out.close()
二、open写文件的几种打开方式:
1、w : 如果文件不存在新建一个,如果文件已经存在,则清空现有内容重新写入。
2、a : 追加写入方式打开,如果文件不存在新建一个,如果文件已存在,在文件末尾追加。这种方式向文件写入内容是都是在尾部追加,即文件读写指针始终处于文件尾部。
3、w+: 读写方式打开,如果文件不存在新建一个,如果文件已存在清空文件,可读写,这里的读是指可以读新写入的内容,而不是原来文件的内容,因为原来文件内容已经清空,如果不希望清空原来文件内容,应该用r+。
4、r+: 读写方式打开,如果文件不存在会有IO错误,如果文件已存在,打开文件,可以读文件内容,也可以写入新内容,注意写入时是覆盖方式写入,而不是插入式。
w+,r+的读写还有不少细节,暂时搁置以后再深入。
三、使用with处理文件,好处是python会自动处理文件关闭问题。
#不用with处理时代码 try: man_file = open('man_data.txt','w') other_file = open('other_data','w') print(man,file = man_file) print(other,file=other_file) except IOError as err: print('File error: '+str(err)) #用str函数将err转换成字符串 finally: if 'man_file' in locals(): man_file.close() if 'other_file in locals(): other_file.close() #使用with处理时代码 try: with open('man_data.txt','w') as man_file: print(man,file=man_file) with open('other_data.txt','w') as other_file: print(other.file=other_file) except IOError as err: print('File error: ' + str(err)) #with可以同时处理多个文件 try: with open('man_data.txt','w') as man_file , open('other_data.txt','w') as other_file: print(man,file=man_file) print(other,file=other_file) except IOError as err: print('File error: ' + str(err))
四、使用pickle保存和加载Python数据对象,如果不是要定制输出格式的话,使用pickle标准库会更有效率,而且通用。
pickle.dump保存数据,pickle.load载入数据
import pickle try: with open('man_data.txt','wb') as man_file , open('other_data.txt','wb') as other_file: pickle.dump(man,man_file) pickle.dump(other,other_file) except IOError as err: print('File error: ' + str(err)) except pickle.PickleError as perr: print('Pickling error: '+str(perr))