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://codercto.com/courses/l/8.html
Advanced Web Metrics with Google Analytics
Brian Clifton / Sybex / 2008 / USD 39.99
Are you getting the most out of your website? Google insider and web metrics expert Brian Clifton reveals the information you need to get a true picture of your site's impact and stay competitive usin......一起来看看 《Advanced Web Metrics with Google Analytics》 这本书的介绍吧!