How we can truncate a file at a given size using Python?

PythonServer Side ProgrammingProgramming

The method truncate([size]) 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, so if you call truncate without arguments, file will be truncated to 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. An example of truncate:

>>> # test.txt contents:
>>> # ABCDE
>>> f = open('test.txt', 'r+')
>>> f.truncate(2)
>>> f.read()
'AB'

Note that this method doesn't work with file open in read only mode.

raja
Published on 22-Dec-2017 11:46:13
Advertisements