Python os.ftruncate() 方法



Python 的 os.ftruncate() 方法截断与给定文件描述符对应文件的末尾数据。它会将文件数据缩减到指定的长度。

如果指定的长度大于或等于文件大小,则文件保持不变。

语法

以下是 ftruncate() 方法的语法:

os.ftruncate(fd, length)

参数

Python 的 os.ftruncate() 方法接受以下参数:

  • fd - 这是需要截断的文件描述符。

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

返回值

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!!

示例

在以下示例中,我们使用 os.ftruncate() 方法与文件对象一起使用。我们使用“with”语句打开和关闭文件。我们将字符串写入文件,将其截断为 8 个字节,然后从开头读取以打印剩余的字符串。

import os

# Open a file 
with open("foo.txt", "r+") as file:
    # Writing to the file
    file.write("Python with Tutorialspoint")
    
	# 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
python_files_io.htm
广告

© . All rights reserved.