1、打開文件的模式主要有,r、w、a、r+、w+、a+
file = open('test.txt',mode='w',encoding='utf-8') file.write('hello,world!') file.close() #由此txt文件內容為hello,world!
2、r+:可讀可寫,根據光標所在位置開始執行。先寫的話,光標在第一個位置---覆蓋寫,后讀的時候根據光標所在位置往后讀;但不管讀幾個字符,讀過后,光標在文末
建議:操作時,讀和寫分開比較好,編碼時涉及到中文用utf-8
file = open('test.txt',mode='r+',encoding='utf-8') file.write('Monday!') content = file.read() #content = file.read(6),表示讀取6個字符,但只要讀過后,光標會在文末 file.close() #由此txt文件內容為:Monday!hello,world! print(content) #打印結果為:hello,world!
file = open('test.txt',mode='r+',encoding='utf-8') content = file.read() file.write('Monday!') file.close() #由此txt文件內容為:hello,world!Monday! print(content) #打印結果為:hello,world!
3、w+:可讀可寫。不管w還是w+,存在文件會清空重寫,不存在文件會新建文件寫;
因為會清空重寫,所以不建議使用
file = open('test.txt',mode='w+',encoding='utf-8') file.write('哮天犬!') file.close() #由此txt文件內容為:哮天犬!
4、a:追加寫。如果文件存在追加寫,如果文件不存在,則新建文件寫
file = open('test.txt',mode='a',encoding='utf-8') file.write('哮天犬!') file.close() #由此txt文件內容為:哮天犬!哮天犬!
5、讀寫多行操作
寫多行
file = open('test.txt',mode='a',encoding='utf-8') file.writelines(['\n二哈!','\n土狗!']) #此處的\n為換行 file.close() 文件內容: 哮天犬! 二哈! 土狗!
讀多行
file = open('test.txt',mode='r',encoding='utf-8') content = file.readlines() #讀出的為列表 file.close() print(content) 控制台輸出:['哮天犬!\n', '二哈!\n', '土狗!']
總結:a:建議使用時讀寫操作分離,即不建議使用w+、r+、a+
b:寫的話,不建議使用w,建議使用a;讀的話,使用r
c:使用中文時,編碼要使用utf-8