简体   繁体   English

Python写入文件返回空文件

[英]Python write to a file returns empty file

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.这将返回一个空文件。

Python won't flush the file after each write . Python 不会在每次write后刷新文件。 You'll either need to flush it manually usingflush :您要么需要使用flush手动刷新它:

>>> f.flush()

or close it yourself withclose :或者自己与关闭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 with before trying to execute it.但是,如果您想在 REPL 中工作,您可能需要坚持手动关闭它,因为它会在尝试执行之前尝试读取整个with

You need to close the file:您需要关闭文件:

>>> f.close()

Also, I would recommend using the with keyword 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.它会自动为您关闭它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM