写操作,w清空原内容再写入,a追加写入
f = open(‘test.txt‘, ‘a‘, encoding=‘utf-8‘) f.write(‘hello\n‘) f.write(‘你好\n‘) f.close()
读取操作
f = open(‘test.txt‘, ‘r‘, encoding=‘utf-8‘) data = f.read(5) #读取5个字符,缺省参数时读取全部 print(data) f.close()
读取一行
f = open(‘test.txt‘, ‘r‘, encoding=‘utf-8‘) data = f.readline() print(data) f.close()
读取多行
f = open(‘test.txt‘, ‘r‘, encoding=‘utf-8‘) data = f.readlines() for i in data: print(i.strip()) f.close()
按字节循环读取文件
f = open(‘test.txt‘, ‘r‘, encoding=‘utf-8‘) date = f.tell() #读取光标当前位置 print(date) i=0; while 1: i=i+1 s = f.read(10) #读取10个单位,一个英文和数字就是一个是1个单位,一个中文是3个单位 if s == ‘‘: break print(s) date = f.tell() print(date) f.seek(0) #调整光标的位置为0 f.close() #关闭文件
原文:https://www.cnblogs.com/weiyuchao/p/12061352.html