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()
The truncate() method resizes the file to the given number of bytes. If the size is not specified, the current position will be used.
w. Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
The truncate command can be used to force a file to be a certain size, by either reducing or enlarging it. Let's look at a few examples to see how to use it. We'll start out with a very basic text file that contains 11 bytes of data.
While it's not useful to truncate when opening in 'w' mode, it is useful in 'r+'. Though that's not the OP's question, I'm going to leave this here for anyone who gets lead here by Google as I did. Let's say you open (with mode 'r+', remember there is no 'rw' mode) a 5 line indented json file and modify the json.load -ed object to be only 3 lines.
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.
Python file modes. Don’t confuse, read about very mode as below. r for reading – The file pointer is placed at the beginning of the file. This is the default mode. r+ Opens a file for both reading and writing. The file pointer will be at the beginning of the file. w Opens a file for writing only.
Reading and Writing to files in Python Truncate () method truncate 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With