문제

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?

도움이 되었습니까?

해결책

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': ''}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top