Python write to a file返回空fi

2024-05-10 08:53:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试执行简单的命令,将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"]))

这将返回一个空文件。


Tags: 文件命令defaulthelloworldonhattype
2条回答

Python不会在每次write之后刷新文件。您要么需要使用^{}手动刷新它:

>>> f.flush()

或者用^{}关闭它:

>>> f.close()

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

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

这将确保文件将被关闭,即使抛出异常。不过,如果您想在REPL中工作,您可能需要坚持手动关闭它,因为它会在尝试执行之前尝试读取with的全部内容。

您需要关闭文件:

>>> f.close()

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

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

它会自动为你关闭它们。

相关问题 更多 >