Correct way to write line to file?

后端 未结 14 1925
日久生厌
日久生厌 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:46

    When you said Line it means some serialized characters which are ended to '\n' characters. Line should be last at some point so we should consider '\n' at the end of each line. Here is solution:

    with open('YOURFILE.txt', 'a') as the_file:
        the_file.write("Hello")
    

    in append mode after each write the cursor move to new line, if you want to use w mode you should add \n characters at the end of the write() function:

    the_file.write("Hello\n")
    
    0 讨论(0)
  • 2020-11-21 06:46

    You can also try filewriter

    pip install filewriter

    from filewriter import Writer
    
    Writer(filename='my_file', ext='txt') << ["row 1 hi there", "row 2"]
    

    Writes into my_file.txt

    Takes an iterable or an object with __str__ support.

    0 讨论(0)
  • 2020-11-21 06:48

    To write text in a file in the flask can be used:

    filehandle = open("text.txt", "w")
    filebuffer = ["hi","welcome","yes yes welcome"]
    filehandle.writelines(filebuffer)
    filehandle.close()
    
    0 讨论(0)
  • 2020-11-21 06:51

    If you want to avoid using write() or writelines() and joining the strings with a newline yourself, you can pass all of your lines to print(), and the newline delimiter and your file handle as keyword arguments. This snippet assumes your strings do not have trailing newlines.

    print(line1, line2, sep="\n", file=f)
    

    You don't need to put a special newline character is needed at the end, because print() does that for you.

    If you have an arbitrary number of lines in a list, you can use list expansion to pass them all to print().

    lines = ["The Quick Brown Fox", "Lorem Ipsum"]
    print(*lines, sep="\n", file=f)
    

    It is OK to use "\n" as the separator on Windows, because print() will also automatically convert it to a Windows CRLF newline ("\r\n").

    0 讨论(0)
  • 2020-11-21 06:54

    The python docs recommend this way:

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

    So this is the way I usually do it :)

    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.

    0 讨论(0)
  • 2020-11-21 06:56

    In Python 3 it is a function, but in Python 2 you can add this to the top of the source file:

    from __future__ import print_function
    

    Then you do

    print("hi there", file=f)
    
    0 讨论(0)
提交回复
热议问题