close、flush、read、readline、seek、tell、truncate、write的使用
1.close关闭文件
1 f1= open("ha.log","r+",encoding="utf-8") 2 data = f1.read() 3 f1.close() 4 print(data)
2.flush刷新文件内部缓冲区(强制写入硬盘)
1 #!/usr/bin/env python 2 f2 = open("ha.log", "a+",encoding="utf-8") 3 f2.write("所凝紧锁的眉头") 4 f2.flush() 5 i = input(">>>")
3.read读取指定字节数据
1 #!/usr/bin/env python 2 f1= open("ha.log","r+",encoding="utf-8") 3 4 data = f1.read(3) 5 f1.close() 6 7 print(data)
一行一行循环读 #!/usr/bin/env python f = open("ha.log",'r',encoding="utf-8") #.read() for line in f : print(line)
4.readline仅读取一行数据,可循环读下一行
1 #!/usr/bin/env python 2 f1= open("ha.log","r+",encoding="utf-8") 3 data = f1.readline() 4 f1.close() 5 print(data)
5.seek指定文件中指针位置 tell获取指针位置
1 #!/usr/bin/env python 2 f1= open("ha.log","r+",encoding="utf-8") 3 d = f1.readline(3) 4 print(f1.tell()) 5 print(f1.seek(6)) 6 f1.truncate() 7 print(d) 8 f1.close()
6.truncate截断数据,仅保留指定之前数据
1 #!/usr/bin/env python 2 f1= open("ha.log","r+",encoding="utf-8") 3 d = f1.readline(3) 4 print(f1.tell()) 5 print(f1.seek(6)) 6 f1.truncate() 7 print(d) 8 f1.close()
7.write写内容
1 #!/usr/bin/env python 2 f2 = open("ha.log", "a+",encoding="utf-8") 3 f2.write("所凝紧锁的眉头") 4 f2.flush() 5 i = input(">>>")