Python写入文件返回空文件 [英] Python write to a file returns empty file

查看:218
本文介绍了Python写入文件返回空文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  50复杂性:test%python2.7 
Python2.7.3(默认,2013年2月11日,12:48:32)
[gcc 4.4.6 20120305(Red Hat 4.4.6-4)] linux2
键入help ,版权,信用或许可以获取更多信息。
>>> f = open(/ export / home / vignesh / resres.txt,w)
>>> f.write(hello world)
>>> f.write(\t.join([hello,world]))

这会返回一个空文件。

解决方案

在每个写入。您可能需要使用 flush

 >>> f.flush()

或者使用 close

 >>> f.close()

在真实程序中使用文件时,建议使用<$ c

$ p $ 带有

使用open('some file.txt','w')作为f:
f.write('some text')
#...



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


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

解决方案

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.

这篇关于Python写入文件返回空文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆