文件偏移量
操作
"""
文件偏移量操作:
(1)tell():获取文件偏移量大小
(2)seek(offset[,whence])
功能:移动文件偏移量位置
参数:offset代表相对于某个位置移动的字节数。负数向前,正数向后
whence基准位置默认为0,代表从头开始,1代表当前位置,2表示文件末wei
"""
常见错误
file_01 = open("1.txt", mode="w+", encoding="UTF-8")
file_01.write("i love Python forever")
# 获取文件偏移量位置,此时位于文件末尾
index = file_01.tell()
print(index) # 21
# 默认基准位置为文件末尾,向后移动两个字节数
file_01.seek(2,2)
file_01.write("hello world")
file_01.close()
io.UnsupportedOperation: can't do nonzero end-relative seeks
原因:在打开文件创建对象时,关键字参数mode也就是文件打开方式以二进制打开时,seek的whence参数才可以是1或2。
解决方法:将上述代码中的"w+"改为"wb+"即可