Python中使用feek函数来移动文件指针,方法是: 文件对象.seek (offset[, whence]) offset–开始的偏移量,也就是代表需要移动偏移的字节数 whence:可选,默认值为0。给offset 参数一个定义,表示要从哪个位置开始偏移; 0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。
def writeFile() :fobj = open("abc.txt", "wt+")print(fobj.tell())fobj.write("123")print(fobj.tell())fobj.seek(2, 0)print(fobj.tell())fobj.write("abc")print(fobj.tell())fobj.close()def readFile() :fobj = open("abc.txt","rt+")rows = fobj.read()print(rows)fobj.close()try:writeFile()readFile()except Exception as err:print(err)
运行结果: