Why truncate when we open a file in 'w' mode in python

I am going through Zed Shaw's Python Book. I am currently working on the opening and reading files chapters. I am wondering why we need to do a truncate, when we are already opening the file in a 'w' mode?

print "Opening the file..."
target = open(filename, 'w')

print "Truncating the file. Goodbye!"
target.truncate()

Solution 1:

It's redundant since, as you noticed, opening in write mode will overwrite the file. More information at Input and Output section of Python documentation.

Solution 2:

So Zed Shaw calls truncate() on a file that is already truncated. OK, that's pretty pointless. Why does he do that? Who knows!? Ask him!

Maybe he does it to show that the method exists? Could be, but that would be pretty daft, since I've never needed to truncate a file in my 15 years as a programmer so it has no place in a newbie book.

Maybe he does it because he thinks he has to truncate the file, and he simply isn't aware that it's pointless?

Maybe he does it intentionally to confuse newbies? That would fit with his general modus operandi, which seems to be to intentionally piss people off for absolutely no reason.

Update: The reason he does this is now clear. In later editions he lists this question as a "common question" in the chapter, and tells you to go read the docs. It's hence there to:

  1. Teach you to read the documentation.
  2. Understand every part of code you copy paste from somewhere before you copy-paste it.

You can debate if this is good teaching style or not, I wouldn't know.

The number of "Help I don't understand Zed Shaws book"-questions on SO had dwindled, so I can't say that it's any worse than any other book out there, which probably means it's better than many. :-)