Python File truncate () Method

Prerequisites :

The Truncate () method truncates the file size. If the optional size argument is specified, the file is truncated to (maximum) that size. The default size corresponds to the current position. The current file position does not change. Note that if the specified size exceeds the current file size, the result is platform-dependent: the options are: the file can remain unchanged, grow to the specified size as if it were filled with zeros, or grow to the specified size with undefined new content. 
To truncate a file, you can open the file in append or write mode.

Syntax :

 fileObject.truncate (size)  

See image below for file size.

Let`s change the file size to 100 bytes.

Exit :

With statement

In the above approaches, every time a file is opened, it must be closed explicitly. If you forget to close the file, it can lead to several errors in your code, i.e. many changes to files do not take effect until the file is properly closed. You can use the with assertion to prevent this. Python`s with statement is used to handle exceptions to make your code cleaner and much more readable. This makes it easier to manage shared resources such as file streams. Notice the following code example for how using the with statement makes your code cleaner. There is no need to call file.close () when used with assertion. The with statement itself ensures that resources are acquired and released correctly.

Let`s change the above file to 50 bytes

# Python program for demonstration
# truncate () method


fp = open ( ` file1.txt` , `w` )

# Truncates the file to uk given
# size

fp.truncate ( 100 )

# Closing files
fp.close ()

# Demo Python program
# truncation method used with operator


with open ( `file1.txt` , ` w` ) as fp:

fp.truncate ( 50 )


Note Note: to learn more about the statement,