Python文件操作
#读模式 f = open("abc.txt","r",encoding="utf-8") dat = f.read() print(dat) f.close() #写模式(覆盖) f_write = open("abc.txt","w",encoding="utf-8") f_write.write("111 222 333 5555") f.close() #追加模式 f_add = open("abc.txt","a",encoding="utf-8") f_add.write("\n888\n") f.close()
#句柄 with open("abc.txt","r",encoding="utf-8") as f_read1,\ open("abc.txt","a",encoding="utf-8") as f_add1: print(f_read1.read()) print(f_add1.write("989800000\n"))
#从哪个字节开始读
f_read1.seek()
#截取,截取多少个字节,其实就是写
f_write.truncate()
#read很特殊,5不一定代表5个字节
f_read1.read(5)
#光标所在的位置
f_read1.tell()
#写入硬盘
f_read1.flush()
#查看open文件的编码
f_read1.encoding
#文件读取最后一行,想到seek() f1 = open("abc.txt","rb") def file_read_last(): offs = -10 while True: f1.seek(offs,2) d = f1.readlines() print("seek范围:%s" %offs) print("文件的其它行内容:%s" % (d[-1])) if len(d) > 1: print("文件的最后一行内容:%s" %(d[-1].decode('utf-8'))) break offs*=2 file_read_last()