Python os.ftruncate()方法

2019-10-16 23:04:29

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

語法

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

os.ftruncate(fd, length)

引數

  • fd ? 這是檔案描述符,需要被截斷。
  • length ? 這是檔案需要被截斷的檔案的長度。

返回值

  • 此方法不返回任何值,僅在Unix系統上可用。

範例

以下範例顯示了ftruncate()方法的用法。

#!/usr/bin/python3
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!!