How we can truncate a file at a given size using Python?

ProgrammingPythonServer Side Programming

The file truncate() method is quite effective. The first reason it is referred to as a method rather than a function is that it comprises the file name (i.e., the object of the file) and a dot operator in addition to other factors (i.e. object of file).

Truncation means cutting off. In this case, we define cutting-off in terms of size.

Syntax

Following is the syntax used to truncate the file to a given size −

file.truncate(size)

Sending the parameter to this method is not essential. If the size is given as a parameter, it must be given in bytes.

The truncate() function has no return value. To examine the file's increased size after appropriately applying truncate(), open the file's properties.

Example

Following is an example to truncate a file at a given size −

file = open('TutorialsPoint.txt', 'r+')
# Truncating the file to specified size file.truncate(2) # Close the file file.close()

Output

As an output we will be able to see the changes made in file after truncating.

Using with statement

The file must be explicitly closed each time it is opened in the methods mentioned above. Many file changes do not become effective until the file is properly closed. Therefore, if the file isn't closed properly, the code may have a number of bugs. Using a with statement can help you prevent this.

A file does not need to be called. Use close() when using the "with statement". Resource acquisition and release are ensured by the with statement.

Example

Following is an example to truncate a file using with statement at a gven size −

with open('TutorialsPoint.txt', 'r+') as file: file.truncate(15)

Output

On execting the above program, we will be able to see the changes made in file after truncating.

raja
Updated on 17-Aug-2022 14:09:48

Advertisements