Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 operator >> to print to file

I have the following Python code to write dependency files of a project. It works fine with Python 2.x, but while testing it with Python 3 it reports an error.

depend = None if not nmake:     depend = open(".depend", "a") dependmak = open(".depend.mak", "a") depend = open(".depend", "a") print >>depend, s, 

Here is the error:

Traceback (most recent call last):   File "../../../../config/makedepend.py", line 121, in <module>     print >>depend, s,     TypeError: unsupported operand type(s) for >>:       'builtin_function_or_method' and '_io.TextIOWrapper' 

What is the best way to get this working with Python 2.x and 3.x?

like image 820
José Avatar asked Feb 10 '12 23:02

José


People also ask

How do I print in Python 3?

The print() function doesn't support the “softspace” feature of the old print statement. For example, in Python 2. x, print "A\n", "B" would write "A\nB\n" ; but in Python 3.0, print("A\n", "B") writes "A\n B\n" .

What is print () in Python?

Python print() Function The print() function prints the specified message to the screen, or other standard output device. The message can be a string, or any other object, the object will be converted into a string before written to the screen.


2 Answers

In Python 3 the print statement has become a function. The new syntax looks like this:

print(s, end="", file=depend) 

This breaking change in Python 3 means that it is not possible to use the same code in Python 2 and 3 when writing to a file using the print statement/function. One possible option would be to use depend.write(s) instead of print.

Update: J.F. Sebastian correctly points out that you can use from __future__ import print_function in your Python 2 code to enable the Python 3 syntax. That would be an excellent way to use the same code across different Python versions.

like image 129
David Heffernan Avatar answered Sep 21 '22 17:09

David Heffernan


print() is a function in Python 3.

Change your code to print(s, end="", file=depend), or let the 2to3 tool do it for you.

like image 40
Amber Avatar answered Sep 19 '22 17:09

Amber