I stumbled upon the post, which tells that w+ can truncate a file, whereas r+ file mode can not.
I am having difficulties understanding what truncate means and what file.truncate() does.
I stumbled upon the post, which tells that w+ can truncate a file, whereas r+ file mode can not.
I am having difficulties understanding what truncate means and what file.truncate() does.
Differences between the modes described in the built-in
function open()
Modes
w+
andw+b
open and truncate the file. Modesr+
andr+b
open the file with no truncation.
Where truncate means to remove all bytes from the opened file, i.e. current position at 0
and current file size of 0
bytes.
file.truncate()
as described in the docs
Resize the stream to the given size in bytes (or the current position if size is not specified). The current stream position isn’t changed. This resizing can extend or reduce the current file size. In case of extension, the contents of the new file area depend on the platform (on most systems, additional bytes are zero-filled). The new file size is returned.
truncate()
depending on reading mode r
, r+
, rb
or rb+
Raise an error: io.UnsupportedOperation: truncate
as mode r
only
allows reading a stream.
truncate()
- not specifying size
current position
is 0
:
truncate the file to 0
bytes - behaves the same as using w
or w+
.
current position
changed by using read(n)
or at least
once readline()
:
file size remains the same, truncate returns current size of file.
truncate(size)
current position
truncates the file to
the specified size. If size
is greater than the original file
size fill bytes until size
with the Null
character \x00
.Behave the same as mode r
and raises
io.UnsupportedOperation: truncate
.
Without specifying size
truncate the file at the current position
otherwise truncate file to given size. If necessary fill end of file
with Null
character \x00
to fill additional bytes.
truncate()
behaves the same for writing modes w
, w+
, wb
and wb+
As writing mode w
will truncate the file on open, using
truncate()
returns 0
.
If the file is still 0
bytes, truncate(size)
can be used to define
the file size by filling additional bytes with \x00
.
In crude terms, truncate is about removal of the text from your file starting from the current position until the end of the file.
Assume a file has 5 lines:
file.readline() # reads the first line
file.truncate() # removes the lines 2 through 5.
file.readline() # returns '' since lines have been deleted
file.seek(0) # moves the cursor to the start of the file
file.readline() # reads the first line again