2

I found this code on a project, and I do not know what the >> does. Does anyone have an explanation?

def save(self, fpath=None):
        """
        Save the JSON data to fpath. This is done automatically if the
        game is over.
        """
        if fpath is None:
            fpath = _jsonf % self.eid
        try:
            print >> gzip.open(fpath, 'w+'), self.rawData,
        except IOError:
            print >> sys.stderr, "Could not cache JSON data. Please " \
                                 "make '%s' writable." \
                                 % os.path.dirname(fpath)

I know that this code is taking information from other files and object within the module, and I know how the code works overall. Only the print >> is confusing me. When this module is installed in a directory without write access, the message Could not cache... comes up. The entire file is located here, but I doubt that it will help at all.

Zach P
  • 560
  • 10
  • 30
  • 1
    This question is not a duplicate of the referenced question _"Python How to simply redirect output of print to a TXT file with a new line created for each redirect"_. In the referenced question, the ">>" operator is used as part of a solution but its use is not explained in much detail. In fact I found the referenced question first and since it did not answer my question of what exactly the ">>" operator does, I searched further and found this question. – SeanDav Feb 17 '16 at 12:08

1 Answers1

6

>> prints to a file like object

print also has an extended form, defined by the second portion of the syntax described above. This form is sometimes referred to as “print chevron.” In this form, the first expression after the >> must evaluate to a “file-like” object, specifically an object that has a write() method as described above. With this extended form, the subsequent expressions are printed to this file object. If the first expression evaluates to None, then sys.stdout is used as the file for output.

print statement

In this case it prints an error message to stderr

jamylak
  • 128,818
  • 30
  • 231
  • 230