Python File seek() 方法

Python 教程 · 2019-02-03 15:44:25

概述

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

语法

seek() 方法语法如下:

fileObject.seek(offset[, whence])

参数

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

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

返回值

该函数没有返回值。

实例

以下实例演示了 readline() 方法的使用:

文件 codercto.txt 的内容如下:

1:www.codercto.com
2:www.codercto.com
3:www.codercto.com
4:www.codercto.com
5:www.codercto.com

循环读取文件的内容:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打开文件
fo = open("codercto.txt", "rw+")
print "文件名为: ", fo.name

line = fo.readline()
print "读取的数据为: %s" % (line)

# 重新设置文件读取指针到开头
fo.seek(0, 0)
line = fo.readline()
print "读取的数据为: %s" % (line)


# 关闭文件
fo.close()

以上实例输出结果为:

文件名为:  codercto.txt
读取的数据为: 1:www.codercto.com

读取的数据为: 1:www.codercto.com

点击查看所有 Python 教程 文章: https://www.codercto.com/courses/l/8.html

查看所有标签

The Practice of Programming

The Practice of Programming

Brian W. Kernighan、Rob Pike / Addison-Wesley / 1999-2-14 / USD 49.99

With the same insight and authority that made their book The Unix Programming Environment a classic, Brian Kernighan and Rob Pike have written The Practice of Programming to help make individual progr......一起来看看 《The Practice of Programming》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具