Writing and reading variables in a file in Python
Question: I am new to the Python language and I am scratching my head on how to make my
code create a file where it can define variables and then later read the
variables so they are useable in my code. How would I do this?

Thanks, Chandler.


Answer: [You can use the pickle module to accomplish
this.](http://docs.python.org/2/library/pickle.html#example)

    
    
    import pickle
    

Here's some sample data:

    
    
    key_value_mapping = dict(tuple=(), string='', list=[], int=0, set=set())
    

Provide a path that you want the file to exist at, e.g.:

    
    
    file_location= '/temp/foobar'
    

We need to open a file to write (w) as a binary (b) file (see the `'wb'` flags
being passed to the open function). These two lines demonstrate how to do
this:

    
    
    with open(file_location, 'wb') as file:
        pickle.dump(key_value_mapping, file)
    

Finally, we need to open the file to read (r) it as a binary (b) file, and
retrieve the data:

    
    
    with open(file_location, 'rb') as file:
        data = pickle.load(file)
        print(data)
    
    {'tuple': (), 'set': set(), 'int': 0, 'list': [], 'string': ''}
    

