2014-11-10 16 views

risposta

16

È possibile seguire il EAFP principle e ask for forgiveness:

import pickle 

try: 
    foo = pickle.load(open("var.pickle", "rb")) 
except (OSError, IOError) as e: 
    foo = 3 
    pickle.dump(foo, open("var.pickle", "wb")) 
6

avevo messo in una funzione per la riusabilità, evitare errori di cattura per il flusso di controllo sul file, in quanto è meno efficiente, e mi userebbe i gestori di contesto per aprire il file.

import os 
import pickle 

def read_or_new_pickle(path, default): 
    if os.path.isfile(path): 
     with open(path, "rb") as f: 
      try: 
       return pickle.load(f) 
      except StandardError: # so many things could go wrong, can't be more specific. 
       pass 
    with open(path, "wb") as f: 
     pickle.dump(default, f) 
    return default 

utilizzo:

foo = read_or_new_pickle(path="var.pickle", default=3) 

foo rendimenti 3

foo = read_or_new_pickle(path="var.pickle", default=4) 

e foo restituisce ancora 3.

Certo, il seguente è piuttosto breve ed elegante, ma troppe cose potrebbe andare male, e che avrebbe dovuto prendere tutto (non credete a me provare questo:? import io, pickle; pickle.load(io.BytesIO(b"\x00")) e giocare con il binario):

import pickle 

def read_or_new_pickle(path, default): 
    try: 
     foo = pickle.load(open(path, "rb")) 
    except StandardError: 
     foo = default 
     pickle.dump(foo, open(path, "wb")) 
    return foo 

Stesso utilizzo. Ma sono preoccupato che il file potrebbe non essere chiuso abbastanza velocemente da evitare un errore aprendolo la seconda volta in caso di file vuoto o malformato. Quindi usa il gestore del contesto:

import pickle 

def read_or_new_pickle(path, default): 
    try: 
     with open(path, "rb") as f: 
      foo = pickle.load(f) 
    except StandardError: 
     foo = default 
     with open(path, "wb") as f: 
      pickle.dump(foo, f) 
    return foo 
Problemi correlati