understanding multiple python 'with open' file functions -


i'm having difficult time understanding second 'with open' function here.

so, in first 'with open' part, we've said out = open(save_as_file, 'wb+') , right? (still new using 'with open'). later write , 'with open' automatically closes 'out' file.that part - we're writing response object requests binary in specified save_as_file location until hit 81920th character aka our buffer #.

what's going on in second 'with open'? breaking down same way above, it's pretty fp = open(save_as_file, 'r') , right? make fp, assigned request response object earlier? we're opening save_as_file use reading not reading or extracting it, don't see reason it. if explain in english what's taking place , purpose of second 'with open' part, appreciated.

(don't worry load_from_file function @ end, that's function under class)

def load_from_url(self, url, save_as_file=none):      fp = requests.get(url, stream=true,                       headers={'accept-encoding': none}).raw      if save_as_file none:         return self.load_from_file(fp)      else:         open(save_as_file, 'wb+') out:             while true:                 buffer = fp.read(81920)                 if not buffer:                     break                 out.write(buffer)         open(save_as_file) fp:             return self.load_from_file(fp) 

you correct second with statement opens file reading.

what happens this:

  1. load response url
  2. if save_as_file none:
    1. call load_from_file on response , return result
  3. else:
    1. store contents of response save_as_file
    2. call load_from_file on contents of file , return result

so essentialy, if save_as_file set stores response body in file, processes , returns processed result. otherwise processes response body , returns result.

the way implemented here because load_from_file expects file-like object , easiest way programmer saw of obtaining read file back.

it done keeping response body in memory , using python 3's io module or python 2's stringio provide file-like object uses response body memory, thereby avoiding need read file again.

fp reassigned in second with statement in same way other variable if assigned value.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -