Question

import cStringIO

output = cStringIO.StringIO()
output.write('First line.\n')
print >>output, 'Second line.'

# Retrieve file contents -- this will be
# 'First line.\nSecond line.\n'
contents = output.getvalue()

What does >>output in the print statement on line 5 do?

Was it helpful?

Solution

It redirects the print statement output to an open file-like object. See the print statement documentation:

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.

Essentially, the line is translated to output.write('Second line.' + '\n') asprint` adds a newline to it's output unless the expression ends with a comma.

The syntax is based on the bash append >> syntax (which also influenced C++ << and >> I/O operators); see PEP 214 for a full motivation for why this was chosen.

In Python 3, where print() is a function, you'd write:

print('Second line.', file=output)

instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top