2

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.

Eduard
  • 7,080
  • 5
  • 35
  • 61
  • Possible duplicate of [Confused by python file mode "w+"](https://stackoverflow.com/questions/16208206/confused-by-python-file-mode-w) – Patrick Artner Mar 11 '18 at 17:29
  • The answers to the dupe are far more enlightening then your self answer - see if they clarify things for you and consider closing this question. – Patrick Artner Mar 11 '18 at 17:30

1 Answers1

-1

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
Eduard
  • 7,080
  • 5
  • 35
  • 61