100

Why does trying to print directly to a file instead of sys.stdout produce the following syntax error:

Python 2.7.2+ (default, Oct  4 2011, 20:06:09)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f1=open('./testfile', 'w+')
>>> print('This is a test', file=f1)
  File "<stdin>", line 1
    print('This is a test', file=f1)
                            ^
SyntaxError: invalid syntax

From help(__builtins__) I have the following info:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file: a file-like object (stream); defaults to the current sys.stdout.
    sep:  string inserted between values, default a space.
    end:  string appended after the last value, default a newline.

So what would be the right syntax to change the standard stream print writes to?

I know that there are different maybe better ways to write to file but I really don't get why this should be a syntax error...

A nice explanation would be appreciated!

Noumenon
  • 5,099
  • 4
  • 53
  • 73
alex
  • 1,011
  • 2
  • 7
  • 5
  • 4
    Are you sure? `print()` is python 3.x built-in function, while `print` is python < 3.x operator. The post shows `2.7.2+`. – khachik Feb 16 '12 at 17:31
  • 2
    Did you `from __future__ import print_function` ? In Python < 3, print is a statement: – Ari Feb 16 '12 at 17:32
  • 1
    No! I didn't. Of course you are right. That solves the problem. Dammit! So the documented print in help(\__builtins__) is the future (3.x) version of print which has a different syntax. Thank you very much and you too, kachik – alex Feb 16 '12 at 17:40
  • 2
    IMO, `help(__builtins__)` displaying that at all is a bug. – Wooble Feb 16 '12 at 17:49
  • 4
    ...although, investigating further, python 2.7.2 *does* have a built-in print function, you just can't access it easily normally (`__builtins__.__dict__['print'](value, file=f1)` does work, though). – Wooble Feb 16 '12 at 18:03

6 Answers6

140

If you want to use the print function in Python 2, you have to import from __future__:

from __future__ import print_function

But you can have the same effect without using the function, too:

print >>f1, 'This is a test'
Gandaro
  • 3,427
  • 1
  • 17
  • 19
  • The downside to using `print >>` is that it then won't work in Python 3. The import is the best way to make cross-version compatible code. – Toby Speight Feb 15 '22 at 13:24
73

print is a keyword in python 2.X. You should use the following:

f1=open('./testfile', 'w+')
f1.write('This is a test')
f1.close()
Rémi
  • 525
  • 1
  • 15
  • 26
Simon Bergot
  • 10,378
  • 7
  • 39
  • 55
44

print(args, file=f1) is the python 3.x syntax. For python 2.x use print >> f1, args.

citxx
  • 2,525
  • 17
  • 40
  • 4
    I think you should also mention `from __future__ import print_function`. Then you can use the clear notation in both, Python 2 and 3. – Martin Thoma Feb 12 '15 at 21:01
  • 2
    I get `AttributeError: 'str' object has no attribute 'write'` with your python3 syntax – Suncatcher Jul 28 '17 at 18:01
  • 6
    @Suncatcher, you are probably trying to pass string containing file name as f1 instead of the actual file object. You need to open file for writing first: `f1 = open('path_to_your_file', 'w')` – citxx Jul 29 '17 at 13:58
  • Yeah, I thought it should be filename, not file object. – Suncatcher Jul 29 '17 at 14:15
15

This will redirect your 'print' output to a file:

import sys
sys.stdout = open("file.txt", "w+")
print "this line will redirect to file.txt"
Tom Hundt
  • 1,694
  • 19
  • 18
Daoctor
  • 412
  • 5
  • 8
13

You can export print statement to file without changing any code. Simply open a terminal windows and run your code in this way:

python yourcode.py >> log.txt
DarkMoon
  • 147
  • 1
  • 4
6

In Python 3.0+, print is a function, which you'd call with print(...). In earlier version, print is a statement, which you'd make with print ....

To print to a file in Python earlier than 3.0, you'd do:

print >> f, 'what ever %d', i

The >> operator directs print to the file f.

Nam Nguyen
  • 1,765
  • 9
  • 13
  • I'd like to print a whole array to the file. If I use your code, only the head and tail of array was printed, like the output from terminal. How to print all array lines to the file? – Sigur Jun 01 '17 at 14:13
  • 2
    @Sigur "Like the output from terminal" Sorry, but the bug's elsewhere. You're not telling Python to print the whole thing, which is why it's not. – wizzwizz4 Dec 06 '17 at 19:59