python file文件函数

python file.seek(offset[,whence]) 函数 用来移动文件指针到指定位置,通过该函数我们可以指定从哪里开始读取或者写入文件。

语法

file.seek(offset[,whence])

参数

参数说明必须/可选
offset偏移量,单位是字节必须
whence

从哪里开始偏移,默认值为0

  • 0代表从文件开头开始算起,
  • 1代表从当前位置开始算起,
  • 2代表从文件末尾算起。
可选

返回值

没有返回值

例子

现介绍一个简单的例子了解该函数的使用方法。

文件内容如下:

python文件函数file.seek()
yxjc123.com 介绍python文件函数的使用。
这是该文件的第3行内容。
这是该文件的第4行内容。

这里结合open(),file.read()、file.close() 函数介绍该函数的使用:

#!/usr/bin/python
# coding=utf-8
file = open('d:\\yxjc123.txt', mode='r+', encoding='utf-8')  # 打开文件
content = file.read(22)  # 读取22字节
print('第一次读取:', content)
file.seek(22)  # 移动文件指针
content = file.read(22)  # 再次读取文件
print('第二次读取:', content)
file.close()  # 关闭文件

输出:

python file.seek():移动文件指针到指定位置

我们看到file.read()和file.seek()的单位似乎有所不同。这里需要改为二进制的方式'rb' 打开文件,然后再读取的时候使用decode()函数解码,可以保持单位一致。

修改如下:

#!/usr/bin/python
# coding=utf-8
file = open('d:\\yxjc123.txt', mode='rb')  # 打开文件
content = file.read(20).decode(encoding='utf-8')  # 读取22字节
print('第一次读取:', content)
file.seek(20)  # 移动文件指针
content = file.read(20).decode(encoding='utf-8')  # 再次读取文件
print('第二次读取:', content)
file.close()  # 关闭文件 
python file.seek():移动文件指针到指定位置