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 alread
When you open a file in write mode, you truncate the original (everything that was there before is deleted). Then whatever you write is added to the file. The problem is, write wants to add information from the beginning, and raises an IOError when the pointer is left at the end. For this type of writing you want to use append (open the file with the 'a+' argument).
With truncate()
, you can declare how much of the file you want to remove, based on where you're currently at in the file. Without parameters, truncate()
acts like w, whereas w always just wipes the whole file clean. So, these two methods can act identically, but they don't necessarily.