Change language

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) 

Example:
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 )

Output:

Note Note: to learn more about the statement,

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method