Retrieving Python data from disk storage

We retrieve two lists vine_x and vine_y from the stored file curley_vine_1.txt. We want them to be in exactly the same form they were in before they were sent for storage.

Getting ready

The preparation for this recipe was done by running the previous program save_curly_vine_1.py. If this ran successfully, there will be a file curly_vine_1.txt inside /constr/vector_shapes. If you open the text file you will see two lines, the first line being the string representation of our original vine_x and similarly the second line of this file will represent vine_y.

# retrieve_curly_vine_1.py
#>>>>>>>>>>>>>>>>>>>>>
#vine_x = []
vine_1 = open('/constr/vector_shapes/curley_vine_1.txt', 'r')
vine_x = eval(vine_1.readline())
vine_y = eval(vine_1.readline())
# Tests to confirm that everything worked.
print "vine_x = ",vine_x
print vine_x[31]
print "vine_y = ",vine_y
print vine_y[6]

How it works...

This works so simply and elegantly because of the eval() function. The documentation says: "The expression argument is parsed and evaluated as a Python expression" and "The return value is the result of the evaluated expression". This is a way of saying that the text inside the brackets is treated as if it were plain Python expressions and executed as such. In our particular example, the string inside the curly brackets is interpreted as a list of numbers, not characters which is what we desire.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.170.134