Python写入文件返回空文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18048728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:48:26  来源:igfitidea点击:

Python write to a file returns empty file

pythonpython-2.7file-io

提问by Vignesh

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

我正在尝试执行简单的命令将 hello world 写入文件:

50 complexity:test% python2.7
Python 2.7.3 (default, Feb 11 2013, 12:48:32)
[GCC 4.4.6 20120305 (Red Hat 4.4.6-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f=open("/export/home/vignesh/resres.txt","w")
>>> f.write("hello world")
>>> f.write("\t".join(["hello","world"]))

This returns an empty file.

这将返回一个空文件。

采纳答案by icktoofay

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

Python 不会在每个write. 您要么需要使用flush以下方法手动刷新它:

>>> f.flush()

or close it yourself with close:

或自己关闭它close

>>> f.close()

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

在实际程序中使用文件时,建议使用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 withbefore trying to execute it.

这确保文件将被关闭,即使抛出异常也是如此。但是,如果您想在 REPL 中工作,您可能希望坚持手动关闭它,因为它会with在尝试执行之前尝试读取整个内容。

回答by Vignesh

You need to close the file:

您需要关闭文件:

>>> f.close()

Also, I would recommend using the withkeyword with opening files:

另外,我建议在with打开文件时使用关键字:

with open("/export/home/vignesh/resres.txt","w") as f:
    f.write("hello world") 
    f.write("\t".join(["hello","world"]))

It will automatically close them for you.

它会自动为您关闭它们。