文件大boss

1.write()  写命令

f=open("a2.txt",'w',encoding='utf-8')
f.write()
f.close()

2.closed  判断是否是关闭的

1 print(f.closed)
>>>False

3.encoding   查看文件编码

1 f=open("a2.txt",'w',encoding='utf-8')
2 print(f.encoding)
>>>utf-8

4.read()  读文件   以什么方式读就以什么方式打开

1 f=open("a2.txt",'w',encoding='utf-8')
2 data=f.read()
3 print(data)

.readline()  读一行

f=open("a2.txt",'r',encoding='utf-8')
print(f.readline())
>>>111111

.readlines()  读成一个列表 , 把每一行读成列表的元素

1 f=open("a2.txt",'r',encoding='utf-8')
2 print(f.readlines())
>>>['11111111111 ', '222222222222222 ', '33333333333333333 ', '444444444444444444444 ', '555555555555555 ', '66666666666666666 ', '77777777777777 ', '888888888888888 ', '999999999999 ']

5.flush()  刷新  相当于保存  ,把内存里的刷到硬盘上

1 f=open("a2.txt",'w',encoding='utf-8')
2 f.flush()

.tall()  获取光标的位置   

1 f=open("a2.txt",'r',encoding='utf-8')
2 print(f.tell())
3 f.readline()     有个回车
4 print(f.tell())
>>> 0
  13

.truncate 截取 

1 f=open("a2.txt",'r+',encoding='utf-8')
2 f.truncate(10)   #截取前10个字节

.seek()  默认参数是 0光标向后移动        以'rb'd的方式读    1  是相对位置    2 倒着移动光标

1 f=open("a2.txt",'r')
2 print(f.tell())
3 f.seek(10)        #向后移动10个字节
4 print(f.tell())
>>> 0
  10
f=open("a2.txt",'rb')
print(f.tell()) #相对位置
f.seek(10,1)
print(f.tell())
f.seek(10,1)
print(f.tell())
>>> 0
  10
  20
f=open("a2.txt",'rb')
f.seek(-10,2) #倒着移动光标
print(f.tell())
>>>


boss   查看最后一行的boss

 1 f=open("a2.txt",'rb')
 2 for i in f:
 3     offs=-10
 4     while True:
 5         f.seek(offs,2)
 6         data=f.readlines()
 7         if len(data)>1:
 8             print(data[-1].decode('utf-8'))
 9             break
10         offs*2
原文地址:https://www.cnblogs.com/shizhengwen/p/6145052.html