Python3 File seek() 方法

Python 3 教程 · 2019-02-07 05:58:34

概述

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/python3

# 打开文件
fo = open("codercto.txt", "r+")
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 3 教程 文章: https://www.codercto.com/courses/l/10.html

查看所有标签

Chinese Authoritarianism in the Information Age

Chinese Authoritarianism in the Information Age

Routledge / 2018-2-13 / GBP 115.00

This book examines information and public opinion control by the authoritarian state in response to popular access to information and upgraded political communication channels among the citizens in co......一起来看看 《Chinese Authoritarianism in the Information Age》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

URL 编码/解码
URL 编码/解码

URL 编码/解码

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

RGB CMYK 互转工具