python - somefile.close 和 somefile.close() 之间的区别

标签 python file python-2.7

想象一下,您在 Python 中打开了某个文件(无论是用于读取、写入还是其他)。我刚刚注意到,当您想关闭该文件时,您可以输入:

somefile.close()

或者您可以输入:

somefile.close

两个版本都是正确的并且它们正确地关闭文件。有什么区别(如果有的话)?

编辑:句子“两个版本都是正确的,并且它们正确地关闭了文件。”是完全错误的。您可以在接受的答案中看到原因。

最佳答案

第一个有用的线索是在 REPL 中运行这两个命令的结果:

>>> f = open("asdf.txt","r")
>>> f.close
<built-in method close of file object at 0x7f38a1da84b0>
>>> f.close()
>>> 

因此,f.close 本身返回一个方法,您可以调用该方法。例如,您可以这样写:

>>> x = f.close
>>> x()

关闭文件。

因此,仅输入 f.close 实际上是不够的,因为它仅返回一个允许您关闭文件的方法。我什至可以证明这一点:创建一个文件并将其命名为 example.txt

然后尝试以下代码:

Type "help", "copyright", "credits" or "license" for more information.
>>> f = open("example.txt","r")
>>> f.close
<built-in method close of file object at 0x7f3d411154b0>
>>> f.readlines()
['this is an example\n', 'file\n']

因此,如果我们只编写f.close,我们仍然可以使用f.readlines():这证明文件实际上并未“关闭”尚未访问!

另一方面,如果我们使用f.close():

Type "help", "copyright", "credits" or "license" for more information.
>>> f = open("example.txt","r")
>>> f.close()
>>> f.readlines()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file
>>> 

这就是前面断言的证明:f.close()f.close 实际上做同样的事情。 f.close() 实际上关闭文件,而 f.close 只是返回一个关闭文件的方法。

<小时/>

在这个答案中,我使用了Python 2.7.4。我不知道 f.close()f.close 的行为在 Python 3+ 中是否有不同。

关于python - somefile.close 和 somefile.close() 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25719138/

相关文章:

python - 使用 python 和 selenium 更改输入字段的值并按 Enter 键

file - 从VHDL文件中的单行读取不同的数据

python - 在Windows x64上编译Python模块

python - 值错误 : Unable to configure handler 'file' : [Errno 13] Permission denied:

python - 无法找到包 python-pip Ubuntu 20.04

python - 为什么这种Python多线程方法比单线程方法需要更多的时间来解决相同的任务?

python - Pandas:相互评估两个数据帧

python - 未绑定(bind)本地错误: local variable <var> referenced before assignment

c - 如何使用C计算目录中的文件

c# - 以 Angular 发布文件