Python 文件 tell() 使用方法及示例

由网友 大卫 发布 阅读 3

Python 文件 tell() 使用方法及示例

Python File(文件) 方法

概述

tell() 方法返回文件的当前位置,即文件指针当前位置。

语法

tell() 方法语法如下:

fileObject.tell()

参数

返回值

返回文件的当前位置。

示例

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

文件 div.cn.txt 的内容如下:

1:www.div.cn
2:www.div.cn
3:www.div.cn
4:www.div.cn
5:www.div.cn

循环读取文件的内容:

# 打开文件
fo = open("div.cn.txt", "r")
print("文件名为: ", fo.name)
line = fo.readline()
print("读取的数据为: %s" % (line))
# 获取当前文件位置
pos = fo.tell()
print("当前位置: %d" % (pos))
# 关闭文件
fo.close()

以上示例输出结果为:

文件名为:  div.cn.txt
读取的数据为: 1:www.div.cn
当前位置: 17

Python File(文件) 方法

Python 文件 truncate() Python 文件 seekable()