Correct way to write line to file in Python
Question: I'm used to doing `print >>f, "hi there"`

However, it seems that `print >>` is getting deprecated. What is the
recommended way to do the line above?

**Update** : Regarding all those answers with `"\n"`...is this universal or
Unix-specific? IE, should I be doing `"\r\n"` on Windows?


Answer: You should use the new print() statement, available with Python 2.6+

    
    
    from __future__ import print_function
    print("hi there", file=f)
    

The alternative would be to use:

    
    
    f = open('myfile','w')
    f.write('hi there\n') # python will convert \n to os.linesep
    f.close() # you can omit in most cases as the destructor will call it
    

Quoting from [Python
documentation](https://docs.python.org/2/tutorial/inputoutput.html#reading-
and-writing-files) regarding newlines:

> On output, if newline is None, any `'\n'` characters written are translated
> to the system default line separator, `os.linesep`. If newline is `''`, no
> translation takes place. If newline is any of the other legal values, any
> `'\n'` characters written are translated to the given string.

