一.读写数据
1.读数据
#使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。
file_object = open('thefile.txt') try: all_the_text = file_object.read( ) finally: file_object.close( )
#注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法。
#读文本文件 input = open('data', 'r') #第二个参数默认为r input = open('data')
2.写数据
file_object = open('content.txt', 'w') file_object.write(content) file_object.writelines(list_of_text_strings) #写入多行 file_object.close()
注意,调用writelines写入多行在性能上会比使用write一次性写入要高。
完整:https://www.cnblogs.com/allenblogs/archive/2010/09/13/1824842.html
追加数据
f = open('test.txt', 'a', encoding='utf8') f.write(' ') f.write('abc') f.close()