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

yipeiwu_com5年前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


相关文章

Ruby元编程基础学习笔记整理

笔记一: 代码中包含变量,类和方法,统称为语言构建(language construct)。 # test.rb class Greeting def initialize(te...

Python序列循环移位的3种方法推荐

第一种方法:特点是直接、容易理解,缺点是速度慢,只能实现循环左移。 def demo(lst, k): temp = lst[:] for i in range(k):...

使用Windows批处理和WMI设置Python的环境变量方法

大概在Python2.7.xx以前,安装Python时环境变量是需要自己设的,所以自己做了一个批处理文件.bat来设置环境变量Path,通过WMI命令wmic来实现。 ::检查pat...

Python实现二叉堆

Python实现二叉堆

优先队列的二叉堆实现 在前面的章节里我们学习了“先进先出”(FIFO)的数据结构:队列(Queue)。队列有一种变体叫做“优先队列”(Priority Queue)。优先队列的出队(De...

Python字典底层实现原理详解

在Python中,字典是通过散列表或说哈希表实现的。字典也被称为关联数组,还称为哈希数组等。也就是说,字典也是一个数组,但数组的索引是键经过哈希函数处理后得到的散列值。哈希函数的目的是使...