Correct way to write line to file?

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

    If you are writing a lot of data and speed is a concern you should probably go with f.write(...). I did a quick speed comparison and it was considerably faster than print(..., file=f) when performing a large number of writes.

    import time    
    
    start = start = time.time()
    with open("test.txt", 'w') as f:
        for i in range(10000000):
            # print('This is a speed test', file=f)
            # f.write('This is a speed test\n')
    end = time.time()
    print(end - start)
    

    On average write finished in 2.45s on my machine, whereas print took about 4 times as long (9.76s). That being said, in most real-world scenarios this will not be an issue.

    If you choose to go with print(..., file=f) you will probably find that you'll want to suppress the newline from time to time, or replace it with something else. This can be done by setting the optional end parameter, e.g.;

    with open("test", 'w') as f:
        print('Foo1,', file=f, end='')
        print('Foo2,', file=f, end='')
        print('Foo3', file=f)
    

    Whichever way you choose I'd suggest using with since it makes the code much easier to read.

    Update: This difference in performance is explained by the fact that write is highly buffered and returns before any writes to disk actually take place (see this answer), whereas print (probably) uses line buffering. A simple test for this would be to check performance for long writes as well, where the disadvantages (in terms of speed) for line buffering would be less pronounced.

    start = start = time.time()
    long_line = 'This is a speed test' * 100
    with open("test.txt", 'w') as f:
        for i in range(1000000):
            # print(long_line, file=f)
            # f.write(long_line + '\n')
    end = time.time()
    
    print(end - start, "s")
    

    The performance difference now becomes much less pronounced, with an average time of 2.20s for write and 3.10s for print. If you need to concatenate a bunch of strings to get this loooong line performance will suffer, so use-cases where print would be more efficient are a bit rare.

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

    Regarding os.linesep:

    Here is an exact unedited Python 2.7.1 interpreter session on Windows:

    Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on
    win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import os
    >>> os.linesep
    '\r\n'
    >>> f = open('myfile','w')
    >>> f.write('hi there\n')
    >>> f.write('hi there' + os.linesep) # same result as previous line ?????????
    >>> f.close()
    >>> open('myfile', 'rb').read()
    'hi there\r\nhi there\r\r\n'
    >>>
    

    On Windows:

    As expected, os.linesep does NOT produce the same outcome as '\n'. There is no way that it could produce the same outcome. 'hi there' + os.linesep is equivalent to 'hi there\r\n', which is NOT equivalent to 'hi there\n'.

    It's this simple: use \n which will be translated automatically to os.linesep. And it's been that simple ever since the first port of Python to Windows.

    There is no point in using os.linesep on non-Windows systems, and it produces wrong results on Windows.

    DO NOT USE os.linesep!

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

    Since 3.5 you can also use the pathlib for that purpose:

    Path.write_text(data, encoding=None, errors=None)

    Open the file pointed to in text mode, write data to it, and close the file:

    import pathlib
    
    pathlib.Path('textfile.txt').write_text('content')
    
    0 讨论(0)
  • 2020-11-21 06:40

    This should be as simple as:

    with open('somefile.txt', 'a') as the_file:
        the_file.write('Hello\n')
    

    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)
    0 讨论(0)
  • 2020-11-21 06:43

    I do not think there is a "correct" way.

    I would use:

    with open ('myfile', 'a') as f: f.write ('hi there\n')
    

    In memoriam Tim Toady.

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

    One can also use the io module as in:

    import io
    my_string = "hi there"
    
    with io.open("output_file.txt", mode='w', encoding='utf-8') as f:
        f.write(my_string)
    
    0 讨论(0)
提交回复
热议问题