"print >> file" ok. What about "print > file" to truncate?

Andrew Dalke dalke at acm.org
Sun Sep 3 22:44:51 CEST 2000


Bengt Richter wrote:
>truncating a file
>to zero length before writing can be useful. ">>" seems to
>mean "append" implicitly, so why not borrow the other redirection
>symbol? (No doubt you can accomplish this other ways, but not as
>concisely?)

To create a new file,

  open("filename", "w")

This creates the file if it doesn't exist, and truncates it if it does.
Because of garbage collection, there's no need for an explicit close,
so that's all you really need to have.

If you use the '>' operator than it would have to be

  fileobject = open("filaname", "w")
  print > fileobject "",

where the fileobject already was created with an open command.
In addition, you see the '"",' ?  That's because you want to suppress
the newline which print normally does, so you need the semicolon.
But "print ," is not proper syntax, so you have to put an expression
in as well - in this case, the empty string.

Finally, suppose the file object is really an file-*like* object,
like a StringIO object:

  import StringIO
  outfile = StringIO.StringIO()
  print >>outfile, "Hello!"

would leave outfile with the value "Hello!\n".  So to work correctly
would likely mean 'print >' calls outfile.truncate(0), but to quote
from the manual
> Availability of this function depends on the operating system
> version (e.g., not all Unix versions support this operation).

So all around, '>' doesn't add expressive power, isn't portable and
(most relvant) no one has asked for that sort of feature in the 3 or
4 years I've been reading this newsgroup, as compared to people asking
for a '>>' mechanism.

                    Andrew
                    dalke at acm.org






More information about the Python-list mailing list