How to Use the Python File truncate() Method

09/18/2021

Contents

In this article, you will learn how to use the Python File truncate() method.

File truncate() Method

The truncate() method in Python is used to truncate the contents of a file to a specified size. This method is available for file objects in both read and write mode.

Here’s an example of how to use the truncate() method in Python:

# Open a file in write mode
file = open("example.txt", "w")

# Write some content to the file
file.write("This is the first line.\n")
file.write("This is the second line.\n")
file.write("This is the third line.\n")

# Close the file
file.close()

# Open the file in read mode
file = open("example.txt", "r")

# Read the contents of the file
contents = file.read()
print("Before truncation:")
print(contents)

# Close the file
file.close()

# Open the file in write mode again
file = open("example.txt", "w")

# Truncate the file to the first 20 bytes
file.truncate(20)

# Close the file
file.close()

# Open the file in read mode again
file = open("example.txt", "r")

# Read the contents of the file again
contents = file.read()
print("After truncation:")
print(contents)

# Close the file
file.close()

In this example, we first create a file named “example.txt” and write some content to it using the write() method. We then close the file and open it again in read mode to verify that the contents have been written to the file.

Next, we open the file in write mode again and use the truncate() method to truncate the file to the first 20 bytes. We then close the file and open it again in read mode to verify that the contents have been truncated.

When we run the above code, it will output the following:

Before truncation:
This is the first line.
This is the second line.
This is the third line.

After truncation:
This is the first line.

As we can see, the contents of the file have been truncated to the first 20 bytes, which only includes the first line of the original content.