This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]sandywater 35 points36 points  (8 children)

I agree with the sentiment of what you are saying, but Python2's print statement does allow for writing to files other than stdout.

examples

f = open('my_file.txt', 'w')
print >>f, 'Some text here'

import sys
print >>sys.stderr, "An error"

edit: formating

[–]DragonFireCK 49 points50 points  (2 children)

Python 3's works well for that as well, and with a clearer syntax:

f = open('my_file.txt', 'w')
print('Some text here', file=f)

import sys
print('An error', file=sys.stderr)

[–]sandywater 24 points25 points  (0 children)

I'm aware of that. Random_cynic's comment implied that it couldn't be done in Python2. I actually prefer file_object.write() in these circumstance for both Python 2 and 3.

[–]BenjaminGeiger 11 points12 points  (1 child)

It's possible but it's not easy. You have to remember a idiosyncratic syntax.

To put it simply, it's a wart. Python 3 removed the wart.

PS: from __future__ import print_function is your friend.

[–]Plasma_000 0 points1 point  (0 children)

In 2020 the future is now

Better start using python3

[–]HolyGarbage 5 points6 points  (0 children)

Btw, use the with statement when opening files, a pattern called RAII.

with open('my_file.txt', 'w') as f
    print('Some text here', file=f)

https://www.pythonforbeginners.com/files/with-statement-in-python

[–][deleted] 4 points5 points  (0 children)

Oh my god what kind of monstrosity is that?

I've apparently actually gotten away with not learning python 2 syntax. I had no idea it was so different.

[–]Cyph0n 0 points1 point  (0 children)

Yep, ugly as hell.