Python write to a file returns empty file

后端 未结 2 1018
长发绾君心
长发绾君心 2020-11-28 15:12

I am trying to do simple commands to write hello world to a file:

50 complexity:test% python2.7
Python 2.7.3 (default, Feb 11 2013, 12:48:32)
[GCC 4.4.6 2012         


        
2条回答
  •  情书的邮戳
    2020-11-28 15:39

    Python won't flush the file after each write. You'll either need to flush it manually using flush:

    >>> f.flush()
    

    or close it yourself with close:

    >>> f.close()
    

    When using files in a real program, it is recommended to use with:

    with open('some file.txt', 'w') as f:
        f.write('some text')
        # ...
    

    This ensures that the file will be closed, even if an exception is thrown. If you want to work in the REPL, though, you might want to stick with closing it manually, as it'll try to read the entirety of the with before trying to execute it.

提交回复
热议问题