Issue
How do I make my code create a file where it store variables and then later read the variables from the file so they are usable in my code.
How would I do this?
Solution
You can use the pickle module to accomplish this.
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': ''}
Answered By - Aaron Hall
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.