ITPub博客

首页 > IT职业 > IT职场 > python中seek怎么用

python中seek怎么用

IT职场 作者:wzzhujun 时间:2021-09-11 10:24:58 0 删除 编辑


概述

seek() 方法用于移动文件读取指针到指定位置。

语法

seek() 方法语法如下:

fileObject.seek(offset[, whence])

参数

offset -- 开始的偏移量,也就是代表需要移动偏移的字节数

whence:可选,默认值为 0。给offset参数一个定义,表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。

file.seek(off, whence=0):

从文件中移动off个操作标记(文件指针),正往结束方向移动,负往开始方向移动。

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

#!/usr/bin/python
# -*- coding: utf-8 -*-
 
# 文件定位测试
# 打开一个文件
fo = open("foo.txt", "r+")
allstr = fo.read()
print "全部内容:n", allstr
print "当前指针位置: ", fo.tell()
print 35*"="
 
# 指针调到开始
position = fo.seek(0, 0)
 
str = fo.read(3)
print "读取前三个字符串是:", str
 
# 查找当前位置
position = fo.tell()
print "当前指针位置: ", position
print 35*"="
 
# 把指针再次重新定位到当前位置开始
position = fo.seek(2, 1)
print "上一个指针移动2个,现在位置: ", fo.tell()
a = fo.read(2)
print "从指针位置读取2个字符为: ", a
print "当前指针位置: ", fo.tell()
print 35*"="
 
# 把指针再次重新定位到从末尾开始
position = fo.seek(-3, 2)
print "从末尾倒数3个,指针位置为: ", fo.tell()
a = fo.read()
print "从指针位置读取字符串: ", a
print "当前指针位置: ", fo.tell()
 
# 关闭打开的文件
fo.close

foo.txt内容为:weiruoyu

输出结果为:

全部内容:
weiruoyu
当前指针位置:  8
===================================
读取前三个字符串是: wei
当前指针位置:  3
===================================
上一个指针移动2个,现在位置:  5
从指针位置读取2个字符为:  oy
当前指针位置:  7
===================================
从末尾倒数3个,指针位置为:  5
从指针位置读取字符串:  oyu
当前指针位置:  8

python学习网,大量的免费python视频教程,欢迎在线学习!

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3370/viewspace-2835074/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-14

  • 博文量
    83
  • 访问量
    729