python - file.write 仅在交互式 python session 退出时执行?

标签 python

我发现了一种我不理解的行为,希望有人能够阐明它。

它看起来像交互式 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/

相关文章:

python - 使用 ajax 间歇性出现 Flask-Login 问题

python - 从 django 管理中删除添加另一个

Python dfply 包 - 加入

python - 列表理解 - 默认第一个值

python - 错误: cluster.名称不是elasticsearch中可识别的选项

python - 如何在Python中为单个语句抛出超过1个可能的异常

python - Flask 应用仅显示 1 张图像,不显示其他图像

python - SymPy 中的非顺序替换

python - 在圆周上生成随机点(python)

python - 有没有一种简单的方法可以用 Python 编写这个?