Pickleing

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sirdeltalot
    New Member
    • Jun 2008
    • 7

    Pickleing

    Hi
    I'm a total beginner in python.
    Want i want to know is how to pickle a dictionary after a user has updated it then read back from the pickled file.
    Thanks
    Iz
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    I used to use the following functions for saving and recalling a dictionary or list of dictionaries to a file using pickle.
    [code=Python]import pickle

    def import_data(fil e_name):
    try:
    f = open(file_name, "r")
    except IOError, e:
    # unable to open file
    Warning("Defaul t file import error. Reverting to original defaults...")
    return None

    # file open is successful
    try:

    dd = pickle.Unpickle r(f).load()
    f.close()
    # test for a dictionary or list of dictionaries
    if isinstance(dd, dict):
    return dd
    elif isinstance(dd, list):
    for i, item in enumerate(dd):
    if not isinstance(item , dict):
    Warning("**INVA LID** List item %s is not a dictionary." % (i))
    return None
    # always return one dictionary
    ddr = {}
    for d in dd: ddr.update(d)
    return ddr
    else:
    # dd is not a dictionary or list of dictionaries
    Warning("Invali d imported data type.\nData must be a dictionary or list of dictionaries.")
    return None

    except:
    # file is not compatible with Unpickler - close file and warn user
    f.close()
    Warning("Invali d defaults file. Reverting to original defaults...")
    return None

    def export_data(fil e_name, dd):
    if check_Defaults_ dir(os.path.dir name(file_name) ):
    # directory exists or was created
    try:
    f = open(file_name, "w")
    pickle.Pickler( f).dump(dd)
    f.close()
    return True
    except:
    Warning("Defaul t values file export error.")
    return False

    else:
    # directory did not exist and the user chose 'no' to create directory
    Warning("The default values file export was aborted")
    return False[/code]

    Comment

    • sirdeltalot
      New Member
      • Jun 2008
      • 7

      #3
      That's realy helpful,
      Thanks!

      Comment

      Working...