os.ftruncate() 方法



描述

ftruncate() 方法截斷與檔案描述符 fd 對應的檔案,使其大小最多為 length 位元組。

語法

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

os.ftruncate(fd, length)

引數

  • fd − 需要截斷的檔案描述符。

  • length − 需要截斷檔案的大小。

返回值

此方法不返回值。適用於類 Unix 系統。

示例

以下示例演示了 ftruncate() 方法的使用:

import os, sys

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

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

# Now you can use ftruncate() method.
os.ftruncate(fd, 10)

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

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

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

Read String is : This is te
Closed the file successfully!!
python_os_file_directory_methods.htm
廣告