Perché provare a stampare direttamente su un file invece di sys.stdoutprodurre il seguente errore di sintassi:
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
Dalla guida (__ builtins__) ho le seguenti informazioni:
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.
Quindi quale sarebbe la sintassi giusta per modificare il flusso standard di scrittura in stampa?
So che ci sono diversi modi forse migliori per scrivere su file, ma davvero non capisco perché questo dovrebbe essere un errore di sintassi ...
Una bella spiegazione sarebbe apprezzata!
from __future__ import print_function? In Python <3, print è una dichiarazione:
help(__builtins__)dimostrarlo è un bug.
__builtins__.__dict__['print'](value, file=f1)funziona, però).
print()è la funzione incorporata di python 3.x, mentreprintè l'operatore python <3.x. Il post mostra2.7.2+.