Ask coding questions

← Back to all posts
Import objects from user input? (Python)
MuffinsTheCat

I am working on a game where the player can have multiple save games at once, and the player has to input the name of the savefile they want. How do I then convert their input into importing their chosen savefile?

Voters
DanishAsyrani
WilliamVoellner
MuffinsTheCat
Comments
hotnewtop
RYANTADIPARTHI

Solution

try an if statement.

something like that.
it should work

MuffinsTheCat

@RYANTADIPARTHI Yes this would work but the game works as the save file having the same name as the player

19wintersp

What language is this in? (And note that files made by programs on Replit will not persist)

MuffinsTheCat
19wintersp

@MuffinsTheCat What you would do is take the user's input specifying the file, open the file, parse its contents, and use that as the data. Here's a small example:

However, as I said initially, be wary that changes made to files by programs on Replit will not persist.

MuffinsTheCat

@19wintersp While this would work, the game gets saved as a .py file then imported later so the usual f = open will not work for this. Do you have any way to make something like

work? I tried this but it tries to import the name of the object rather than the object itself

19wintersp

@MuffinsTheCat That's not how imports generally work, and you probably shouldn't do things in this way. Could you explain what is being saved into that file? There is likely a better solution - though there is a way (hack) of doing this.

MuffinsTheCat

@19wintersp Basically this is how one thing gets saved:

19wintersp

@MuffinsTheCat Since you're not executing any script there, why do you need to save it as a Python file? You could use a custom key/value system:

(a better version would stop keys and values from having "=" in them, and maybe use a dictionary) or you could use a built-in serialisation library like for JSON:

MuffinsTheCat

@19wintersp Thank you for your help. I understand that I would repeat

for every value but replacing health, but how do I do this with classes and lists?

19wintersp

@MuffinsTheCat The other issue with using a Python file to do this is that the file is executed, meaning of someone tried to load a maliciously-crafted save file, unintended arbitrary code execution could take place. For example, if it was made so that "health" was "1;print('hacked')", the savefile would be this:

When imported, this save file will print "hacked".

19wintersp

@MuffinsTheCat If you want to preserve the classes, you may want to look into Pickle, but that has loads of other issues. To save a list, just put it into the dictionary as you would for a regular Python dictionary. You can generate a dictionary from an object with the __dict__ property, and assign to __dict__ too.