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?
It redirects the print
statement output to an open file-like object. See the print
statement documentation:
>>
must evaluate to a “file-like” object, specifically an object that has awrite()
method as described above. With this extended form, the subsequent expressions are printed to this file object. If the first expression evaluates toNone
, thensys.stdout
is used as the file for output.
Essentially, the line is translated to output.write('Second line.' + '\n') as
print` 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.