我发现了一种我不理解的行为,希望有人能够阐明它。
它看起来像交互式 python session (都使用 ipython 并且直接调用 python3 cmd)仅在退出 session 时写入文件。
(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:~$
这种行为是预期的吗?如果是这样为什么?
如果这种行为是意外的,知道为什么会这样吗?
最佳答案
您没有调用 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
关于python - file.write 仅在交互式 python session 退出时执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30767733/