Correct way to write line to file?

后端 未结 14 1924
日久生厌
日久生厌 2020-11-21 06:27

I\'m used to doing print >>f, \"hi there\"

However, it seems that print >> is getting deprecated. What is the recommended way t

相关标签:
14条回答
  • 2020-11-21 06:58

    When I need to write new lines a lot, I define a lambda that uses a print function:

    out = open(file_name, 'w')
    fwl = lambda *x, **y: print(*x, **y, file=out) # FileWriteLine
    fwl('Hi')
    

    This approach has the benefit that it can utilize all the features that are available with the print function.

    Update: As is mentioned by Georgy in the comment section, it is possible to improve this idea further with the partial function:

    from functools import partial
    fwl = partial(print, file=out)
    

    IMHO, this is a more functional and less cryptic approach.

    0 讨论(0)
  • 2020-11-21 07:00

    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 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 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.

    0 讨论(0)
提交回复
热议问题