python-操作文件指针seek()使用

python中可以使用seek()移动文件指针到指定位置,然后读/写。通常配合 r+ 、w+、a+ 模式,在此三种模式下,seek指针移动只能从头开始移动,即seek(x,0) 。

模式默认写方式与seek()配合---写与seek()配合---读
r+文件指针在文件头部,即seek(0)覆盖f = open('test.txt','r+',encoding='utf-8')f.seek(3,0)f.write('aaa') #移动文件指针到指定位置,再写f = open('test.txt','r+',encoding='utf-8')f.seek(3,0)f.read() #移动文件指针到指定位置,读取后面的内容
w+文件指针在文件头部,即seek(0)清除f = open('test.txt','w+',encoding='utf-8')f.seek(3,0)f.write('aaa') #清除文件内容,移动文件指针到指定位置,再写f = open('test.txt','w+',encoding='utf-8')f.write('aaa') f.seek(3,0)f.read()#清除文件内容写入,移动文件指针到指定位置,读取后面内容
a+文件指针在文件尾部,即seek(0,2)追加f = open('test.txt','a+',encoding='utf-8') f.seek(3,0) f.write('aaa') #直接在文件末尾写入,seek移动指针不起作用同 r+
(1)seek(offset[,whence]):
(2)offset--偏移量,可以是负值,代表从后向前移动;
(3)whence--偏移相对位置,分别有:os.SEEK_SET(相对文件起始位置,也可用“0”表示);os.SEEK_CUR(相对文件当前位置,也可用“1”表示);os.SEEK_END(相对文件结尾位置,也可用“2”表示)。

seek(x,0):表示指针从开头位置移动到x位置
seek(x,1):表示指针从当前位置向后移动x个位置
seek(-x,2):表示指针从文件结尾向前移动x个位置
例:file.seek(-1,2),文件指针从文件末尾向前移动一个字符,配合read相关方法/函数可读取该字符。
import os

f = open("ljf.txt","w+")

f.write("my name is ljf ,please input your name:")
f.close()

f = open("ljf.txt","r+")
f.read()


f = open('ljf.txt',"rw+")  #首先先创建一个文件对象,打开方式为w
print(f.read(3))  #用read()方法读取并打印
print (f.tell()) #打印出文件指针的位置
f.seek(0, os.SEEK_END)  #用seek()方法操作文件指针(把文件指针移到文件末尾位置并移动0)
offset = f.tell()

f.write("let's continue my code")
print ("-"*15)  
f.seek(offset, 0) 
print(f.read(15))
print(f.tell())  #打印出文件指针的位置
f.close()  #关闭文件

发布于 2021-06-02 08:53