print or write on a text file ?

F

Franck Ditter

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,

franck
 
W

Wayne Werner

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
 
T

Terry Reedy

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 ?

print converts objects to strings and adds separators and terminators.
If you have a string s and want to output it as is, out.write(s) is
perhaps faster. It is 6 chars shorted than print(s, file=out).
There should be a printlines, like readlines ?

No, now that files are iterators, I believe readlines is somewhat obsolete.

file.readlines() == list(file)

The only reason not to deprecate it is for the hint parameter to limit
the bytes read. That is little harder to do with the iterator.


If you have any iterator of lines,
for line in lines: line.print()
is quite sufficient. There is little or no need for output limitation.
 
N

nn

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,

    franck

There is

out.writelines(lst)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,821
Latest member
AleidaSchi

Latest Threads

Top