Home » Python

Python File truncate() Method with Example

Python File truncate() Method: Here, we are going to learn about the truncate() method, how to resize a file in Python?
Submitted by IncludeHelp, on December 24, 2019

File truncate() Method

truncate() method is an inbuilt method in Python, it is used to truncate the file based on the given size.

Syntax:

    file_object.truncate(size)

Parameter(s):

  • size – It's an optional parameter and its default value is "None" that means current file position.

Example:

# Python File truncate() Method with Example

# creating a file
myfile1 = open("hello1.txt", "w")

# writing text to the file
myfile1.write("Python is an interpreted, high-level, general-purpose programming language")

# truncating the file
myfile1.truncate(20)

# closing the file
myfile1.close()

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

# closing the file
myfile1.close()

Output

Python is an interpr


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.