What does print >> do in python?

In Python 2, the print >> syntax was used to redirect print output to a file-like object. This syntax has been removed in Python 3, where you use the file parameter instead.

Python 2 Syntax with >> Operator

The syntax was print >> file_object, "message" where the output gets redirected to the specified file object.

Example - Redirecting to a File

Here's how to redirect print output to a file in Python 2 ?

# Python 2 syntax
file_obj = open("output.txt", "w")
print >> file_obj, "Hello, World!"
file_obj.close()

This writes "Hello, World!" to the output.txt file instead of displaying it on the console.

Example - Redirecting to Standard Error

You could also redirect to standard error stream ?

import sys
# Python 2 syntax
print >> sys.stderr, "Error: Something went wrong!"

This sends the error message to the standard error stream instead of standard output.

Python 3 Alternative - Using file Parameter

Python 3 replaced the >> syntax with the file parameter in the print() function ?

# Python 3 syntax
with open("output.txt", "w") as file_obj:
    print("Hello, World!", file=file_obj)

For standard error redirection ?

import sys
print("Error: Something went wrong!", file=sys.stderr)

Key Differences

Aspect Python 2 Python 3
Syntax print >> file, "text" print("text", file=file)
Type Statement Function
Parentheses Optional Required

Migration Example

Converting Python 2 code to Python 3 ?

# Python 2 (deprecated)
f = open("log.txt", "w")
print >> f, "Debug message"
print >> sys.stderr, "Error occurred"

# Python 3 (current)
with open("log.txt", "w") as f:
    print("Debug message", file=f)
    print("Error occurred", file=sys.stderr)

Conclusion

The print >> syntax was Python 2's way of redirecting output to files or streams. Python 3 replaced this with the cleaner file parameter in the print() function, providing the same functionality with better syntax.

Updated on: 2026-03-24T17:18:29+05:30

531 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements