Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python对文件的写入返回空文件_Python_Python 2.7_File Io - Fatal编程技术网

Python对文件的写入返回空文件

Python对文件的写入返回空文件,python,python-2.7,file-io,Python,Python 2.7,File Io,我正在尝试执行简单的命令将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("/ex

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

这将返回一个空文件。

您需要关闭该文件:

>>> f.close()
此外,我建议在打开文件时使用
with
关键字:

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

它将自动为您关闭它们。

Python不会在每次
写入后刷新文件。您需要使用以下方法手动刷新它:

或者自己用以下方法将其关闭:

在实际程序中使用文件时,建议将
一起使用:

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

这样可以确保即使引发异常,文件也会关闭。但是,如果您想在REPL中工作,您可能希望继续手动关闭它,因为它将在尝试执行它之前尝试使用
读取整个

您需要
f.close()
。是时候用
语句学习
。我认为这不应该被否决。OP充分解释了他的问题,展示了他的代码,并提出了一个真实的问题。仅仅因为他不熟悉Python并不是惩罚他的理由。@Keyser-好吧,我想你可以这么说。哦,好吧,现在这个问题已经开始了,所以对于任何未来从事研究的程序员来说都是如此
>>> f.close()
with open('some file.txt', 'w') as f:
    f.write('some text')
    # ...