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
廣告