print or write on a text file ?

Wayne Werner wayne at waynewerner.com
Fri Sep 28 17:33:30 EDT 2012


On Fri, 28 Sep 2012, Franck Ditter wrote:

> Hi !
> Here is Python 3.3
> Is it better in any way to use print(x,x,x,file='out')
> or out.write(x) ? Any reason to prefer any of them ?
> There should be a printlines, like readlines ?
> Thanks,

The print function automatically appends newlines to the end of what it 
prints.

So if you had

text = 'Hello!'

and you did:

print(text, file=outfile)

then outfile would contain 'Hello!\n'

In contrast, outfile.write(text) would only write 'Hello!'. No newline.

There are lots of other handy things you can do with the print function:

values = [1,2,3,4]
print(*values, sep='\n', file=outfile)

I'll leave it to you to experiment.
HTH,
Wayne



More information about the Python-list mailing list