Python中tell()方法的使用详解

yipeiwu_com6年前Python基础

 tell()方法返回的文件内的文件读/写指针的当前位置。
语法

以下是tell()方法的语法:

fileObject.tell()

参数

  •     NA

返回值

此方法返回该文件中读出的文件/写指针的当前位置。
例子

下面的例子显示了tell()方法的使用。

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name

# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line

line = fo.readline()
print "Read Line: %s" % (line)

# Get the current position of the file.
pos = fo.tell()
print "Current Position: %d" % (pos)

# Close opend file
fo.close()

当我们运行上面的程序,它会产生以下结果:

Name of the file: foo.txt
Read Line: This is 1st line

Current Position: 18


相关文章

python面向对象 反射原理解析

一、静态方法(staticmethod)和类方法(classmethod) 类方法:有个默认参数cls,并且可以直接用类名去调用,可以与类属×××互(也就是可以使用类属性) 静态方法:让...

如何更优雅地写python代码

前言 Python 这门语言最大的优点之一就是语法简洁,好的代码就像伪代码一样,干净、整洁、一目了然。但有时候我们写代码,特别是 Python 初学者,往往还是按照其它语言的思维习惯来写...

python3处理含有中文的url方法

python3处理含有中文的url方法

如下所示: from urllib.parse import quote import string url = r'http://www.xxxx.com/name=中文' ur...

python中while循环语句用法简单实例

本文实例讲述了python中while循环语句用法。分享给大家供大家参考。具体如下: number = 1 while number < 20: print(number)...

python机器人运动范围问题的解答

机器人的运动范围Python实现: 问题:地上有个 m 行 n 列的方格。一个机器人从坐标(0,0)的格子开始移动,它每一次可以向左、右、上、下移动一格,但不能进入行坐标和列坐标的数位之...