Python 文件 tell() 方法



Python 文件的 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 文件 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

示例

在此示例中,我们将尝试在每次将新行追加到演示文件时确定光标位置。首先,我们以追加模式(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("Tutorialspoint")

# 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
python_file_methods.htm
广告