Python方法ftruncate()截断文件描述符fd对应的文件,使其最大长度为字节。

os.ftruncate(fd, length) - 语法

os.ftruncate(fd, length)
  • fd         -  这是需要截断的文件描述符。

  • length  -  这是需要截断文件的长度。

os.ftruncate(fd, length) - 示例

以下示例显示ftruncate()方法的用法。

#!/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, "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!!

参考链接

https://www.learnfk.com/python/os-ftruncate.html