Python os.ftruncate() 方法



Python 的 os.ftruncate() 方法截斷與給定檔案描述符對應檔案的末尾資料。它會將檔案資料縮減到指定的長度。

如果指定的長度大於或等於檔案大小,則檔案保持不變。

語法

以下是 ftruncate() 方法的語法:

os.ftruncate(fd, length)

引數

Python 的 os.ftruncate() 方法接受以下引數:

  • fd - 這是需要截斷的檔案描述符。

  • length - 這是需要截斷檔案的檔案長度。

返回值

Python 的 os.ftruncate() 方法不返回任何值。

示例

以下示例顯示了 ftruncate() 方法的使用。在這裡,我們以讀/寫模式開啟一個檔案,然後刪除除前 10 個位元組之外的檔案資料。

#!/usr/bin/python
import os, sys

# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# Write one string
os.write(fd, b"This is test - This is test")

# using ftruncate() method.
os.ftruncate(fd, 10)

# Now read this file from the beginning
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print ("The available String : ", str)

# Close opened file
os.close( fd )
print ("Closed the file successfully!!")

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

The available String :  b'This is te'
Closed the file successfully!!

示例

在以下示例中,我們使用 os.ftruncate() 方法與檔案物件一起使用。我們使用“with”語句開啟和關閉檔案。我們將字串寫入檔案,將其截斷為 8 個位元組,然後從開頭讀取以列印剩餘的字串。

import os

# Open a file 
with open("foo.txt", "r+") as file:
    # Writing to the file
    file.write("Python with Tutorialspoint")
    
	# Flush the write buffer
    file.flush()
	
    # get the file descriptor
    fd = file.fileno()

    # Truncating the file
    os.ftruncate(fd, 8)

    # Read the file
    file.seek(0)
    print(file.read())

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

Python w
python_files_io.htm
廣告