file.write仅在退出交互式python会话时执行?

时间:2015-06-10 21:36:20

标签: python

我发现了一种我不理解的行为,希望有人可以对此有所了解。

看起来交互式python会话(使用ipython并直接调用python3 cmd)只在我退出会话时写入文件。

(ipython)dev:~$ ipython
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
Type "copyright", "credits" or "license" for more information.

IPython 3.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: outfile = open('outfile','w')

In [2]: outfile.write('test')
Out[2]: 4

In [3]: outfile.close
Out[3]: <function TextIOWrapper.close>

In [4]: !ls -l outfile
-rw-rw-r-- 1 jjk3 jjk3 0 Jun 10 14:32 outfile

In [5]: quit
(ipython)dev:~$ ls -l outfile
-rw-rw-r-- 1 jjk3 jjk3 4 Jun 10 14:33 outfile
(ipython)dev:~$

预计会出现这种情况吗?如果是这样的话?

如果这种行为是意料之外的,任何想法为什么会这样做?

1 个答案:

答案 0 :(得分:4)

您没有调用close,因此在退出shell之前文件仍处于打开状态:

outfile.close() # <- add parens

一旦你这样做,你就能看出差异:

In [12]: outfile = open('outfile','w')    
In [13]:  outfile.write('test')    
In [14]:  outfile.close
Out[14]: <function close>    
In [15]: !ls -l outfile
-rw-rw-r-- 1 padraic padraic 0 Jun 10 22:41 outfile    
In [16]:  outfile.close()
In [17]: !ls -l outfile
-rw-rw-r-- 1 padraic padraic 4 Jun 10 22:41 outfile

您应该使用with打开文件并让它为您处理结算:

In [18]: with open('outfile','w') as out:
   ....:     out.write("test")
   ....:        
In [19]: !ls -l outfile
-rw-rw-r-- 1 padraic padraic 4 Jun 10 22:43 outfile