1.write() 写命令
f=open("a2.txt",'w',encoding='utf-8')
f.write()
f.close()
2.closed 判断是否是关闭的
print(f.closed)
>>>False
3.encoding 查看文件编码
f=open("a2.txt",'w',encoding='utf-8')
print(f.encoding)
>>>utf-8
4.read() 读文件 以什么方式读就以什么方式打开
f=open("a2.txt",'w',encoding='utf-8')
data=f.read()
print(data)
.readline() 读一行
f=open("a2.txt",'r',encoding='utf-8')
print(f.readline())
>>>111111
.readlines() 读成一个列表 , 把每一行读成列表的元素
f=open("a2.txt",'r',encoding='utf-8')
print(f.readlines())
>>>['11111111111\n', '222222222222222\n', '33333333333333333\n', '444444444444444444444\n', '555555555555555\n', '66666666666666666\n', '77777777777777\n', '888888888888888\n', '999999999999\n']
5.flush() 刷新 相当于保存 ,把内存里的刷到硬盘上
f=open("a2.txt",'w',encoding='utf-8')
f.flush()
.tall() 获取光标的位置
f=open("a2.txt",'r',encoding='utf-8')
print(f.tell())
f.readline() 有个回车
print(f.tell())
>>> 0
13
.truncate 截取
f=open("a2.txt",'r+',encoding='utf-8')
f.truncate(10) #截取前10个字节
.seek() 默认参数是 0光标向后移动 以'rb'd的方式读 1 是相对位置 2 倒着移动光标
f=open("a2.txt",'r')
print(f.tell())
f.seek(10) #向后移动10个字节
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
f=open("a2.txt",'rb')
for i in f:
offs=-10
while True:
f.seek(offs,2)
data=f.readlines()
if len(data)>1:
print(data[-1].decode('utf-8'))
break
offs*2