Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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() 
like image 947
Animesh Avatar asked Dec 30 '10 11:12

Animesh


People also ask

What does truncating a file in Python mean?

The truncate() method resizes the file to the given number of bytes. If the size is not specified, the current position will be used.

Does open W overwrite Python?

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.

Why would you truncate a file?

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.

Is it possible to truncate when opening a file in w mode?

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.

What is the difference between truncate () and W ()?

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.

What are the modes of Reading and writing in Python?

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.

What does truncate () method do in Python?

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.


1 Answers

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.

like image 113
ismail Avatar answered Oct 23 '22 12:10

ismail