Python os.ftruncate() Method
os.ftruncate() Overview
os.ftruncate() trims the file corresponding to the file descriptor fd, which cannot exceed the maximum file size.
Available on Unix.
os.ftruncate() Syntax
The ftruncate() method syntax format is as follows.
os.ftruncate(fd, length);
os.ftruncate() Parameters
- fd – The descriptor of the file.
- length – the size of the file to crop.
os.ftruncate() Return Value
This method has no return value.
os.ftruncate() Demo#1
The following example demonstrates the use of the ftruncate() method:
#!/usr/bin/python3
import os, sys
# Open file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
# Writing strings
os.write(fd, "This is test - This is test")
# Using the ftruncate() method
os.ftruncate(fd, 10)
# Read Content
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print ("The read string is :", str)
# Close file
os.close( fd)
print ("Close file successfully!!!")
Output:
The read string is :This is te
Close file successfully!!!
os.ftruncate() Demo#2
Use of os.ftruncate() method
# Python program to explain os.ftruncate() method
# importing os module
import os
# Open the file and get
# the file descriptor associated
# with it using os.open() method
fd = os.open("Python_intro.txt", os.O_RDWR)
# Print the original size of the file (in bytes)
print("File size (in bytes):", os.stat(fd).st_size)
# Length (in Bytes) to which
# the file will be truncated
length = 72
# Truncate the file
# to at most given length
# using os.ftruncate() method
os.ftruncate(fd, length)
# Print the content of file
size = os.stat(fd).st_size
print(os.read(fd, size).decode("utf-8"))
# Print the size of file (in bytes)
print("File size (in bytes):", os.stat(fd).st_size)
Output:
File size (in bytes): 409
Content of file Python_intro.txt:
Python is a widely used general-purpose, high level programming language
File size (in bytes): 72
Consider the below text as the new content of the file named Python_intro.txt.
Python is a widely used general-purpose, high level programming language
os.ftruncate() Demo#3
If the specified length exceeds the file size
# Python program to explain os.ftruncate() method
# importing os module
import os
# Open the file and get
# the file descriptor associated
# with it using os.open() method
fd = os.open("Python_intro.txt", os.O_RDWR)
# Print the original size of the file (in bytes)
print("File size (in bytes):", os.stat(fd).st_size)
# Length (in Bytes) to which
# the file will be truncated
length = 100
# Truncate the file
# to at most given length
# using os.ftruncate() method
os.ftruncate(fd, length)
# Print the content of file
size = os.stat(fd).st_size
print(os.read(fd, size).decode("utf-8"))
# Print the size of file (in bytes)
print("File size (in bytes):", os.stat(fd).st_size)
Output:
File size (in bytes): 72
Content of file Python_intro.txt:
Python is a widely used general-purpose, high level programming language
File size (in bytes): 100
Actual file content after truncating file sized 72 bytes to 100 bytes: