天天看點

Python3 os.ftruncate() 方法

Python3 OS 檔案/目錄方法

概述

os.ftruncate() 裁剪檔案描述符fd對應的檔案, 它最大不能超過檔案大小。

Unix上可用。

文法

ftruncate()

方法文法格式如下:

os.ftruncate(fd, length)¶
      

參數

  • fd -- 檔案的描述符。
  • length -- 要裁剪檔案大小。

傳回值

該方法沒有傳回值。

執行個體

以下執行個體示範了 ftruncate() 方法的使用:

#!/usr/bin/python3

import os, sys

# 打開檔案
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# 寫入字元串
os.write(fd, "This is test - This is test")

# 使用 ftruncate() 方法
os.ftruncate(fd, 10)

# 讀取内容
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print ("讀取的字元串是 : ", str)

# 關閉檔案
os.close( fd)

print ("關閉檔案成功!!")
      

執行以上程式輸出結果為:

讀取的字元串是 :  This is te
關閉檔案成功!!