Python 檔案 truncate() 方法



Python 檔案 **truncate()** 方法用於截斷或縮短檔案的大小。換句話說,此方法刪除檔案的內容,並用一些垃圾(或空)值替換它們以保持大小。此檔案的大小預設為檔案中的當前位置。

此方法接受一個可選的 size 引數,檔案將被截斷到(最多)該大小。此引數的預設值為當前檔案位置。但是,如果 size 引數超過檔案的當前大小,則透過向檔案中新增未定義的內容或零來將檔案增加到指定的大小。結果取決於平臺。

**注意** - 如果檔案以只讀模式開啟,則 truncate() 方法將不起作用。

語法

以下是 Python 檔案 **truncate()** 方法的語法:

fileObject.truncate(size)

引數

  • **size** - (可選)要截斷檔案的大小。

返回值

此方法不返回值。

示例

考慮一個包含字串的演示檔案“foo.txt”。

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

以下示例顯示了 Python 檔案 truncate() 方法的用法。

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

# Now truncate remaining file.
fo.truncate()

# Try to read file now
line = fo.readline()
print("Read Line:", line)

# Close opened file
fo.close()

執行上述程式時,會產生以下結果:

Name of the file:  foo.txt
Read Line:
Read Line:

示例

如果我們將 size 引數傳遞給該方法,則檔案的內容將被截斷,但檔案的大小將等於傳遞的引數。

演示檔案“foo.txt”的大小為 138 位元組,size 引數設定為 50 位元組,該方法將刪除當前檔案中的現有內容,並用未定義的內容填充檔案。因此,檔案的大小減小到 50 位元組。

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

# Read the first line of the file
line = fo.readline()
print("Read Line:", line)

# Now truncate the file and maintain the size up to 50 bytes
fo.truncate(50)

# Try to read the file now
line = fo.readline()
print("Read Line:", line)

# Close opened file
fo.close()

執行上面的程式後,將顯示如下輸出,並檢查檔案大小以觀察結果。

Name of the file:  foo.txt
Read Line:
Read Line:

示例

但是,如果給定的 size 引數超過檔案大小,則通常會截斷其中的內容,並且檔案將用未定義的內容或零填充。

演示檔案“foo.txt”的大小為 138 位元組,如果 size 引數設定為 200 位元組,則該方法將用未定義的內容填充檔案,同時將檔案大小保持在 200 位元組。

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

# Read the first line of the file
line = fo.readline()
print("Read Line:", line)

# Now truncate the file and maintain the size up to 200 bytes
fo.truncate(200)

# Try to read the file now
line = fo.readline()
print("Read Line:", line)

# Close opened file
fo.close()

執行上面的程式後,將顯示如下輸出。要檢查檔案的大小,請轉到此檔案的屬性。

Name of the file:  foo.txt
Read Line:
Read Line:

示例

當檔案處於讀取模式 (r 或 r+) 時,此方法不起作用。

在此示例中,檔案以讀取模式 (r+) 開啟,在此檔案的物件上呼叫的 truncate 方法將無效,並保持其內容與之前相同。

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

# Read the first line of the file
line = fo.readline()
print("Read Line:", line)

# Now truncate the file
fo.truncate()

# Try to read the file now
line = fo.readline()
print("Read Line:", line)

# Close opened file
fo.close()

執行上面的程式後,將顯示如下輸出:

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

Read Line: This is 2nd line
python_file_methods.htm
廣告