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!!
上一篇:
Python os模块方法
下一篇:
Python异常处理