python 文件指针及文件覆盖

1、文件纯净模式延伸

r+t:可读、可写

w+t:可写、可读
with open('b.txt','w+t',encoding='utf-8') as f:
print(f.readable())
print(f.writable())
a+t:可追加写、可读

2、控制文件指针移动
方法:f.seek(offset,whence)
offset代表文件指针的偏移量,单位是字节bytes
whence代表参照物,有三个取值
(1)0:参照文件的开头
(2)1:参照当前文件指针所在的位置
(3)2:参照文件末尾
PS:快速移动到文件末尾f.seek(0,2)
强调:其中whence=1和whence=2只能在b 模式下使用
with open(r'rrf.txt','r+b')as f:
# f.readlines()
# f.seek(6,0) #从开头移动6个字节
# print(f.readline().decode('UTF-8') )
# print(f.tell() )

# with open(r'rrf.txt', 'r+b')as f:
# f.readline()
# f.seek(9,1) #从当前指针位置移动9个字节
# print(f.readline() .decode('UTF-8') )

with open(r'rrf.txt', 'r+b')as f:
f.seek(-5,2) #指针在末尾,往前读5个字节
print(f.read() .decode('UTF-8') )
print(f.tell())

3、文件覆盖(修改)方法
(1)在原文件上进行修改操作,再写入原文件
优点:只有一个文件
缺点:如果文件过大会占用内存资源
with open('rrf.txt','r',encoding= 'UTF-8')as f :
x=f.read()
x.replace('我的','qqc') #修改内容
with open('rrf.txt','w',encoding= 'UTF-8')as f:
f.write(x )

(2)将原文件内容修改后写入新的文件,再改名
优点:同一时刻只有一行内容在内存
缺点:有两个文件
import os

with open('rrf.txt','r',encoding= 'UTF-8')as f,\
   open('bbt','w',encoding='UTF-8' )as f1:
for x in f:
f1.write(x.replace('半倚深秋','qq'))

os.remove('rrf.txt') # 删除老文件
os.rename('bbt','rrf.txt') #把新文件名字改成老文件名字


















猜你喜欢

转载自www.cnblogs.com/quqinchao/p/qqczhizhen.html