In Python C = Pickle.load(open(filename, 'r')) Does This Close The File?
Solution 1:
No, but you can simply adapt it to close the file:
# file not yet openedwithopen(fileName, 'r') as f:
# file opened
c = pickle.load(f)
# file opened# file closed
What with
statement does, is (among other things) calling __exit__()
method of object listed in with
statement (in this case: opened file), which in this case closes the file.
Regarding opened file's __exit__()
method:
>>>f = open('deleteme.txt', 'w')>>>help(f.__exit__)
Help on built-in function __exit__:
__exit__(...)
__exit__(*excinfo) -> None. Closes the file.
Solution 2:
I hate to split hairs, but the answer is either yes or no -- depending on exactly what you are asking.
Will the line, as written, close the file descriptor? Yes.
Will it happen automatically after this operation? Yes… but probably not immediately.
Will the file be closed immediately after this line? No, not likely (see reply above).
Python will delete the file descriptor when the reference count for the file object is zero. If you are opening the file in a local scope, such as inside a function (either as you have done, or even if you have assigned it to a local variable inside a def
), when that local scope is cleaned up -- and if there are no remaining references to the file object, the file will be closed.
It is, however, a much better choice to be explicit, and open the file inside a with
block -- which will close the file for you instead of waiting for the garbage collector to kick in.
You also have to be careful in the case where you unintentionally assign the file descriptor to a local variable… (see: opened file descriptors in python) but you aren't doing that. Also check the answers here (see: check what files are open in Python) for some ways that you can check what file descriptors are open, with different variants for whatever OS you are on.
Solution 3:
Yes, the return value of open
has a lifetime only of that of the call to pickle.load
. It closes the open file descriptor when closed.
If you're extremely paranoid, consider:
withopen(fileName,'r') as fin:
c = pickle.load(fin)
The with
keyword establishes the lifetime of fin
Post a Comment for "In Python C = Pickle.load(open(filename, 'r')) Does This Close The File?"