Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | os.truncate() method
Next article icon

Python File truncate() Method

Last Updated : 12 Dec, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisites:

  • File Objects in Python
  • Reading and Writing to files in Python

Truncate() method truncate the file’s size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position. The current file position is not changed. Note that if a specified size exceeds the file’s current size, the result is platform-dependent: possibilities include that the file may remain unchanged, increase to the specified size as if zero-filled, or increase to the specified size with undefined new content.
To truncate the file, you can open the file in append mode or write mode.

Syntax:

  fileObject.truncate(size)  

Example:
See the below image for file size.

Python-truncate-input

Let’s change the file size to 100 bytes.




# Python program to demonstrate
# truncate() method
  
fp = open('file1.txt', 'w')
  
# Truncates the file to specified
# size
fp.truncate(100)
  
# Closing files
fp.close()
 
 

Output:

python-truncate-output

With statement

In the above approaches, every time the file is opened it is needed to be closed explicitly. If one forgets to close the file, it may introduce several bugs in the code, i.e. many changes in files do not go into effect until the file is properly closed. To prevent this with statement can be used. with statement in Python is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Observe the following code example on how the use of with statement makes code cleaner. There is no need to call file.close() when using with statement. The with statement itself ensures proper acquisition and release of resources.

Let’s change the above file to 50 bytes




# Python program to demonstrate
# truncate method using with statement
  
with open('file1.txt', 'w') as fp:
    fp.truncate(50)
 
 

Output:
python-truncate-output

Note: To know more about with statement click here.



Next Article
Python | os.truncate() method
author
rutujakawade24
Improve
Article Tags :
  • Python
  • Technical Scripter
Practice Tags :
  • python

Similar Reads

  • Python | os.truncate() method
    OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.truncate() method in Python is used to truncate the file indicated by the spec
    4 min read
  • Python | os.truncate() method
    os.truncate() method truncates the file corresponding to the path so that it is at the most length bytes in size. This function can support file descriptors too. In this article, we will learn about Python os.truncate() method. os.truncate() Method Syntax in PythonSyntax: os.truncate(path, length) P
    3 min read
  • Python | Decimal sqrt() method
    Decimal#sqrt() : sqrt() is a Decimal class method which returns the Square root of a non-negative number to context precision. Syntax: Decimal.sqrt() Parameter: Decimal values Return: the Square root of a non-negative number to context precision. Code #1 : Example for sqrt() method # Python Program
    2 min read
  • Python | Decimal to_eng_string() method
    Decimal#to_eng_string() : to_eng_string() is a Decimal class method which converts to a string, using engineering notation if an exponent is needed. Syntax: Decimal.to_eng_string() Parameter: Decimal values Return: converts to a string Code #1 : Example for to_eng_string() method # Python Program ex
    2 min read
  • Python - PyTorch trunc() method
    PyTorch torch.trunc() method returns a new tensor with the truncated integer values of the elements of input/ after removing the decimal portion of the number. Syntax: torch.trunc(input, out=None) Arguments input: This is input tensor. out: The output tensor. Return: It returns a Tensor. Let's see t
    1 min read
  • Python String lstrip() Method
    The lstrip() method removes leading whitespace characters from a string. We can also specify custom characters to remove from the beginning/starting of the string. Let's take an example to remove whitespace from the starting of a string. [GFGTABS] Python s = " Hello Python!" res = s.lstrip
    2 min read
  • Python String center() Method
    center() method in Python is a simple and efficient way to center-align strings within a given width. By default, it uses spaces to fill the extra space but can also be customized to use any character we want. Example: [GFGTABS] Python s1 = "hello" s2 = s1.center(20) print(s2) [/GFGTABS]Ou
    2 min read
  • Python | Decimal as_tuple() method
    Decimal#as_tuple() : as_tuple() is a Decimal class method which returns named tuple representation of the Decimal value. Syntax: Decimal.as_tuple() Parameter: Decimal values Return: tuple with values - sign - digits - exponent Code #1 : Example for as_tuple() method # Python Program explaining # as_
    2 min read
  • Python String strip() Method
    strip() method in Python removes all leading and trailing whitespace by default. You can also specify a set of characters to remove from both ends. It returns a new string and does not modify the original. Let's take an example to remove whitespace from both ends of a string. [GFGTABS] Python s =
    2 min read
  • Python String endswith() Method
    The endswith() method is a tool in Python for checking if a string ends with a particular substring. It can handle simple checks, multiple possible endings and specific ranges within the string. This method helps us make our code cleaner and more efficient, whether we're checking for file extensions
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences