Python file truncate() method

Python File truncate() Method

The truncate() method truncates a file to a certain size. If the optional size argument is provided, the file will be truncated to at most that size.

The size defaults to the current position. The current file position is not changed. Note that if the specified size exceeds the file’s current size, the results are platform-dependent.

Note – This method will not work correctly if the file is opened in read-only mode.

Syntax

The syntax of the truncate() method is as follows:

fileObject.truncate([size])

Parameters

  • size – If this optional argument is present, the file will be truncated to (at most) that size.

Return Value

This method does not return any value.

The following example shows the usage of the truncate() method.

Suppose the file ‘foo.txt’ contains the following text –

This is the 1st line
This is the 2nd line
This is the 3rd line
This is the 4th line
This is the 5th line

Example

fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)

line = fo.readline()
print ("Read Line: %s" % (line))

fo.truncate()
line = fo.readlines()
print ("Read Line: %s" % (line))

# Close the opened file
fo.close()

When we run the above program, it produces the following output:

fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)

line = fo.readline()
print ("Read Line: %s" % (line))

fo.truncate()
line = fo.readlines()
print ("Read Line: %s" % (line))

# Close the opened file
fo.close()

When we run the above program, it produces the following output:

fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name) line-numbers">Name of the file: foo.txt
Read Line: This is 1s
Read Line: []

Leave a Reply

Your email address will not be published. Required fields are marked *