Useful Python snippet #1

Found this useful Python snippet in Python Essential Reference by David M.Beazley today. It seems you can write to files in a similar way to how you would with IOStream in C++ by using the ‘>>’ syntax.

Example

f = open('out.txt', 'w')
print >>f, 'Hello, World'
f.close()

Unfortunately this only works in Python 2.x, and will break in Python 3 — so perhaps it is best left alone. Nonetheless, it’s a feature I didn’t realize before today!

Leave a Reply

Your email address will not be published. Required fields are marked *