Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python c = pickle.load(open(fileName, 'r')) does this close the file?

Tags:

python

pickle

I tried to Google but cannot find an answer.

If I just do

c = pickle.load(open(fileName, 'r'))

Will the file be automatically closed after this operation?

like image 941
Yuxiang Wang Avatar asked Aug 01 '13 04:08

Yuxiang Wang


People also ask

Does pickle close the file?

You then open the pickle file for reading, load the content into a new variable, and close up the file. Loading is done through the pickle.

Does pickle load empty file?

pickle doesn't work that way: an empty file doesn't create an empty list. An empty list would look like this in a pickle file: (lp0 . Do note, however, that "the next time you run the program", if the line filename = open("roombooking.

How do I load files in pickle?

Python Pickle load You have to use pickle. load() function to do that. The primary argument of pickle load function is the file object that you get by opening the file in read-binary (rb) mode. Simple!

How do I open a pickle file in Python?

Pickling Files To use pickle, start by importing it in Python. To pickle this dictionary, you first need to specify the name of the file you will write it to, which is dogs in this case. Note that the file does not have an extension. To open the file for writing, simply use the open() function.


1 Answers

No, but you can simply adapt it to close the file:

# file not yet opened
with open(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.
like image 180
Tadeck Avatar answered Oct 05 '22 20:10

Tadeck