The truncate() Method



The method truncate() truncates 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.

Note − This method will not work in case the file is opened in read-only mode.

Syntax

Following is the syntax for truncate() method −

fileObject.truncate( [ size ])

Parameters

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

Return Value

This method does not return any value.

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

Assuming that 'foo.txt' file contains following text −

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 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 opened file
fo.close()

When we run the above program, it produces the following result −

Name of the file: foo.txt
Read Line: This is 1s
Read Line: []
python_file_methods.htm
Advertisements