一.指针移动的单位
-
除了 t 模式下的 read(n) 中的 n 代表的是字符个数
-
其余的移动单位都是以字节为单位
🍉先向文件里写入一串字符
with open(r"test.txt", "w+b")as f:
f.write("abc你好".encode("utf-8"))
🍉 "t"模式下的"read(n)"读得是字符个数
with open('test.txt',mode='rt',encoding='utf-8') as f:
res=f.read(5) # 读5个字符
print(res) # abc你
🍉 非"t"模式下的"read(n)"读得是 Bytes 个数
with open('test.txt', mode='rb') as f:
res = f.read(6) # 读6个 Bytes
print(res.decode("utf-8")) # abc你
二. f.seek( ) : 偏移量
1.格式说明
f.seek([移动的字节格式],[模式])
2.三种模式
0
: 参照文件开头移动指针1
: 参照当前所在的位置移动指针2
: 参照文件末尾位置移动指针
ps : 只有在 0
模式可以在 t
下使用, 1
和 2
只能在 b
下使用
with open('test.txt', mode='rt', encoding='utf-8') as f:
f.seek(3, 0) # 指针跳到文件开头,然后向右移动三个字节
f.seek(3, 1) # "t" 模式下不支持 "1",报错
f.seek(-3, 2) # "t" 模式下不支持 "2",报错
with open('test.txt', mode='rb') as f:
f.seek(3, 0) # 指针跳到文件开头,然后向右移动三个字节
print