Python truncate method:

The truncate() method of IOBase class resizes the stream to the given size in bytes. In other words, the truncate() method truncates the file based on the given size. However, the current stream position isn’t changed. This resizing can extend or reduce the current file size.

Method Signature

The signature for the truncate() method is as shown below.

fileObject.truncate(size)

Method parameters and return type

  • Here, the truncate() method takes one optional parameter to specify the size in bytes.
  • However, it will return an integer value specifying the size.

Python truncate method Examples:

Example 1: In this case, we will open a file in w mode and truncate it to 25 bytes.

# Opening a file
f1 = open("test.txt", "w")

# writing text to the file
f1.write("Python is an interpreted programming language")

# truncating the file
f1.truncate(25)

# closing the file
f1.close()

# reading the file and printing the text
f1 = open("test.txt", "r")
print(f1.read())

# closing the file
f1.close()

Output

Python is an interpreted 

Example 2: In this case, we will open a file in w+ mode and truncate it to 30 bytes.

# Opening a file
f = open("test.txt", "w+") 

# writing text to the file
f.write("This is a test file \n Python Programming\n Programming is fun")

#Reading
f.seek(0)
print(f.read())

# truncating the file
f.truncate(30) 

# closing the file
f.close() 

#open and read the file after the truncate:
print("\n**Opening in Read mode**")
f = open("test.txt", "r") 
print(f.read())
f.close()

Output

This is a test file 
 Python Programming
 Programming is fun

**Opening in Read mode**
This is a test file 
 Python P

Example 3: In this case, we will use truncate to increase the size of the file.

#Opening and writing
f=open("python.txt","w+")
f.write("Welcome to the world of Python Programming")

#Using truncate() method to increase the size
f.truncate(200)

#Reading the file from beginning
f.seek(0)
print("Reading --",f.read())
f.close()

Output

Reading -- Welcome to the world of Python Programming

Conclusion

Hence, the truncate() method resizes the file stream to a given number of bytes.

References

Happy Learning 🙂

Leave A Comment