Python .truncate()

Anonymous contributor's avatar
Anonymous contributor
Published May 10, 2021Updated Aug 11, 2023
Contribute to Docs

The .truncate() file method allows the user to resize the file to a given number of bytes when the file is accessed through the append mode.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

file.truncate(n)

Example

Use .truncate() to change the size of the gullivers_travels.txt file from 603,908 bytes to 100:

f = open("gullivers_travels.txt", "a")
f.truncate(100)
f.close()
f = open("gullivers_travels.txt", "r")
print(f.read())

Codebyte Example

In this example .truncate() is used on my_one_liner.txt reducing the size by two bytes or two characters:

Code
Output

All contributors

Contribute to Docs

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours