Muhamed Huseinbašić
Muhamed Huseinbašić

Reputation: 580

Difference between somefile.close and somefile.close()

Imagine that you opened some file in Python (it doesn't matter is it for reading, or writing or whatever). I just noticed that when you want to close that file you can type:

somefile.close()

or you can type:

somefile.close

Both versions are right and they close file properly. What is the difference (if there is any)?

Edit: Sentence "Both versions are right and they close file properly." is completely wrong. You can see why in accepted answer.

Upvotes: 1

Views: 67

Answers (1)

Newb
Newb

Reputation: 2930

The first useful clue is the result of running both commands in the REPL:

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

So f.close itself returns a method, that you can then call. For example, you could write:

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

To close the file.

So just typing f.close isn't actually enough, as it only returns a method that allows you to close the file. I can even prove this: go make a file and call it example.txt.

Then try out the following code:

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']

So if we just write f.close, we can still use f.readlines(): this is proof that the file isn't actually "closed" to access yet!

On the other hand, if we use 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
>>> 

So that's proof of the previous assertions: f.close() and f.close do in fact not do the same things. f.close() actually closes the file, whereas f.close just returns a method to close the file.


In this answer, I used Python 2.7.4. I don't know if the behavior of f.close() and f.close is any different in Python 3+.

Upvotes: 3

Related Questions