Python写入文件返回空文件

Vig*_*esh 12 python file-io python-2.7

我正在尝试使用简单的命令将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"]))
Run Code Online (Sandbox Code Playgroud)

这将返回一个空文件.

ick*_*fay 19

Python不会在每次之后刷新文件write.你需要手动冲洗它flush:

>>> f.flush()
Run Code Online (Sandbox Code Playgroud)

或者自己关闭close:

>>> f.close()
Run Code Online (Sandbox Code Playgroud)

在真实程序中使用文件时,建议使用with:

with open('some file.txt', 'w') as f:
    f.write('some text')
    # ...
Run Code Online (Sandbox Code Playgroud)

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


iCo*_*dez 5

您需要关闭该文件:

>>> f.close()
Run Code Online (Sandbox Code Playgroud)

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

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

它会自动关闭它们.