- Trending Categories
- Data Structure
- Operating System
- MS Excel
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How we can truncate a file at a given size using Python?
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.
Following is the syntax used to truncate the file to a given 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.
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()
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.
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)
On execting the above program, we will be able to see the changes made in file after truncating.
Kickstart Your Career
Get certified by completing the courseGet Started