view raw
dcrearer dcrearer - 1 year ago 75
Python Question

Python 3.4 support of print operations with redirectors >>

I'm going through some examples from a text book. The source code below fails with the following Traceback:

Traceback (most recent call last):
File "", line 39, in <module>
File "", line 12, in storeDbase
print >> dbfile, key
TypeError: unsupported operand type(s) for >>: 'builtin_function_or_method' and '_io.TextIOWrapper'

def storeDbase(db, dbfilename=dbfilename):
"formatted dump of database to flat file"
import sys
dbfile = open(dbfilename, 'w')
for key in db:
print >> dbfile, key
for (name, value) in db[key].items():
print >> dbfile, name + RECSEP + repr(value)
print >> dbfile, ENDDB

When I run this code under Python 2.7 it works as expected. Can someone please point me in the right direction. What has changed in the
function that prevents this from working in Python 3.4?


In Python 3, print() is a function and not a keyword. So, if you want to redirect the output, you have to set the optional parameter file (default value is sys.stdout), like this:

print(key, file=dbfile)

Take a look at the Print is a function paragraph, from the official documentation about what changed in Python 3.