Correct way to write line to file?

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 "rn" on Windows?


This should be as simple as:

with open('somefile.txt', 'a') as the_file:
    the_file.write('Hellon')

From The Documentation:

Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single 'n' instead, on all platforms.

Some useful reading:

  • The with statement
  • open()
  • 'a' is for append, or use
  • 'w' to write with truncation
  • os (particularly os.linesep )

  • You should use the print() function which is available since Python 2.6+

    from __future__ import print_function  # Only needed for Python 2
    print("hi there", file=f)
    

    For Python 3 you don't need the import , since the print() function is the default.

    The alternative would be to use:

    f = open('myfile', 'w')
    f.write('hi theren')  # 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 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.


    The python docs recommend this way:

    with open('file_to_write', 'w') as f:
        f.write('file contents')
    

    So this is the way I do it do :)

    Statement from docs.python.org:

    It is good practice to use the 'with' keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks.

    链接地址: http://www.djcxy.com/p/5366.html

    上一篇: 不能使用numpy.sign(),但该书可以使用,我不知道为什么

    下一篇: 正确的方式写入文件?