Python os.ftruncate() 方法从与给定文件描述符对应的文件末尾截断数据。它会将文件数据减少到指定的长度。
如果指定的长度大于或等于文件大小,则文件保持不变。
语法
以下是 ftruncate() 方法的语法 -
os.ftruncate(fd, length)
参数
Python os.ftruncate() 方法接受以下参数 -
- fd − 这是需要截断的文件描述符。
- length − 这是需要截断 file 的文件的长度。
返回值
Python os.ftruncate() 方法不返回任何值。
例以下示例显示了 ftruncate() 方法的用法。在这里,我们以读/写模式打开一个文件,然后删除除前 10 个字节以外的文件数据。
#!/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, b"This is test - This is test")
# using ftruncate() method.
os.ftruncate(fd, 10)
# Now read this file from the beginning
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print ("The available String : ", str)
# Close opened file
os.close( fd )
print ("Closed the file successfully!!")
当我们运行上述程序时,它会产生以下结果——
The available String : b'This is te'
Closed the file successfully!!
Closed the file successfully!!
例
在以下示例中,我们将 os.ftruncate() 方法与 File Objects.我们使用 “with” 语句来打开和关闭文件。我们将字符串写入文件,将其截断为 8 个字节,然后从头读取以打印剩余的字符串。
import os
# Open a file
with open("foo.txt", "r+") as file:
# Writing to the file
file.write("Python with qikepu")
# Flush the write buffer
file.flush()
# get the file descriptor
fd = file.fileno()
# Truncating the file
os.ftruncate(fd, 8)
# Read the file
file.seek(0)
print(file.read())
在执行上述程序时,它会产生以下结果 -
Python w