Friday, March 16, 2018

File truncate() Method


File truncate() Method in Python 3

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

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.

Example

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

#!/usr/bin/python3

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: []