python3_文件操作中file.seek()方法

1、seek函数 

 file.seek(off, whence=0):从文件中移动off个操作标记(文件指针),正往结束方向移动,负往开始方向移动。

如果设定了whence参数,就以whence设定的起始位为准,0代表从头开始,1代表当前位置,2代表文件最末尾位置。

file.seek(0)是重新定位在文件的第0位及开始位置
file = open("test.txt","rw") #注意这行的变动
file.seek(3) #定位到第3个 

2、示例

from sys import argv

script,input_file = argv

def print_all(f):
print f.read()

def rewind(f):
f.seek(0)

def print_a_line(line_count,f):
print line_count,f.readline()

current_file = open(input_file)

print "First let's print the whole file:\n"

print_all(current_file)

print "Now let's rewind,kind of like a tape."

rewind(current_file)

print "Now let's print three lines."

current_line = 1
print_a_line(current_line,current_file)

current_line = current_line + 1
print_a_line(current_line,current_file)

current_line = current_line + 1
print_a_line(current_line,current_file)

3、结果

其中test.txt内容如下:

this is the first line content typing in...
我是从键盘输入的内容,准备写入到文件中.
这是第三行。
这是第四行。
这是第五行。


4、示例2

>>> f=open("aaa.txt","w") #以只写的形式打开一个叫做aaa.txt的文件
>>> f.write("my name is liuxiang,i am come frome china") #写入内容
>>> f.close() #关闭文件
>>> f=open("aaa.txt","r") #以只读打开文件
>>> f.read() #读取内容
'my name is liuxiang,i am come frome china'
>>> f.seek(3,0) #“0”代表从文件开头开始偏移,偏移3个单位
>>> f.read(5) #从偏移之后的指针所指的位置(即“n”)开始读取5个字符
'name '
>>> f.tell() #显示现在指针指在哪个位置(即“i”的位置)
>>> f.readline() #读取这一行剩下的内容
'is liuxiang,i am come frome china'

>>> f.seek(0,2) #“2”代表从末尾算起,“0”代表偏移0个单位
>>> f.read()
'' #因为是从末尾算起,内容已结束。所以读取内容为空

猜你喜欢

转载自www.cnblogs.com/mercywym/p/10010146.html