Home > other >  How to export a variable to another python file
How to export a variable to another python file

Time:03-04

Hi all I am creating a game that allows the user to export their progress to another file which can be loaded back up again once they come back. I am wondering if there is a way to export multiple variables to a different file, which will then change the file in the computer's memory. I have a way to import the variables, I just need some help with the exporting part, thank you for your help, Darren.

CodePudding user response:

You can try store the users progress data in JSON file. In python it`s pretty easy, you just need to use json library.

First you should import lib

import json

For example the player`s data looks like this

player_data = {
    'username': 'Nemo',
    'xp': 1000,
    'armor': {
        'name': 'Kaer Morhen armor',
        'weight': 1.57
    }
}

Than you can easely export this data to JSON file

with open("data_file.json", "w") as wf:
    json.dump(player_data, wf)

And import it back

with open("data_file.json", "r") as rf:
    player_data = json.load(rf)

I hope it would be helpful for you :)

  • Related