Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to file.write() or to print to file? [duplicate]

To write to a file called "file.txt", I can either use:

with open('file.txt', 'a') as file:
    file.write('some text')

or :

with open('file.txt', 'a') as file:
    print('some text', file=file)

What are the advantages/disadvantages of each? Are they essentially the same?

like image 416
DarthVlader Avatar asked Oct 16 '25 21:10

DarthVlader


1 Answers

Are they essentially the same?

No. The second code block will append a new line in the output, the first won't.

What are the advantages/disadvantages of each?

print has more features. It allows you to use non-string objects, *args with custom separators, etc.

If all you are doing is writing/printing a single string, then there is not much difference and no particular reason to choose one over the other. But do be aware of the trailing newline in the print (i.e. the default end argument of the print function).

like image 61
wim Avatar answered Oct 18 '25 11:10

wim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!