Python File tell() 方法



Python File tell() 方法用于查找文件中文件光标(或指针)的当前位置。

此方法主要用于需要确定文件光标是位于文件的开头还是结尾的方案。

语法

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


 fileObject.tell()

参数

该方法不接受任何参数。

返回值

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

考虑一个包含 5 行的演示文件 “foo.txt”。让我们尝试在各种情况下对这个文件调用 Python 文件 tell() 方法。

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

以下示例显示了 Python File tell() 方法的用法。在这里,我们将使用 readline() 方法尝试读取演示文件中的第一行。然后,调用 tell() 方法来确定文件指针的当前位置。


# Open a file
fo = open("foo.txt", "r+")
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:", line)

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

# Close opened file
fo.close()

当我们运行上述程序时,它会产生以下结果——

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

Current Position: 18

使用 tell() 方法,我们还可以写入某个位置的文件。在下面的示例中,我们将写入一个空文件,并使用此方法确定最终的文件指针位置。


# Open a file
fo = open("demo.txt", "w")
print("Name of the file: ", fo.name)

# Write into the file using write() method
fo.write("This is a demo file")

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

# Close opened file
fo.close()

一旦我们执行上面的程序,结果就会产生如下 -

Name of the file: demo.txt
Current Position: 19

在此示例中,我们将尝试在每次将一行附加到演示文件时确定光标位置。首先,我们在 append 模式(a 或 a+)中打开一个文件,并使用 tell() 方法显示文件光标位置。然后,我们使用 write() 方法将新内容追加到文件中。将再次记录光标的最终位置。


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

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

# Write into the file using write() method
fo.write("qikepu")

# Get the current position of the file after appending.
pos = fo.tell()
print("Position after appending:", pos)

# Close opened file
fo.close()

上述程序的输出生成如下 -

Name of the file: demo.txt
Current Position: 19
Position after appending: 33

tell() 方法与 seek() 方法齐头并进。在下面的示例中,我们尝试使用 seek() 方法将文件光标设置在特定位置,然后使用 tell() 方法检索此位置集。


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

# Move the pointer backwards using negative offset
fo.seek(18, 0)

line = fo.read()
print("File Contents:", line)

#Using tell() method retrieve the cursor position from the ending
print("File cursor is present at position", fo.tell())

# Close opened file
fo.close()

在执行上面的程序时,输出显示为 -

Name of the file: foo.txt
File Contents: This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
File cursor is present at position 88