0

I am working on a text role-playing-game in Python3, and have encountered an issue saving objects.

I am able to save strings and integers (e.g. representing character name, stats, etc.), but cannot save objects (such as the items or weapons), as I get the error:

write() argument must be str, not Weapon

Here is my code:

elif userinp == 'save':
    save_place = open("rpgsave.txt", "w")
    list_to_write = [strength, agility, dexterity, wisdom, intelligence, charisma, 
                     main_character.name, main_character.weapons, 
                     main_character.mp, main_character.xp, level_counter, job, 
                     free_points, copcoin, cloc.xpos, cloc.ypos, 
                     main_character.health, inventory]
    for i in range(len(list_to_write)):
        unacceptables = [main_character.weapons, inventory]
        if list_to_write[i] in unacceptables:
            if list_to_write[i] == main_character.weapons:
                save_place.write(list_to_write[i])
                save_place.write("\n")
            elif list_to_write[i] == inventory:
                objects = (Weapon, Item)
                for x in range(len(inventory)):
                    save_place.write(inventory[x])
                    save_place.write("\n")
        else:
            list_to_write[i] = str(list_to_write[i])
            save_place.write(list_to_write[i])
            save_place.write("\n")
Destaq
  • 655
  • 9
  • 23
  • 1
    do you want `json.dump(your_dict,f)` – mad_ Mar 05 '20 at 19:05
  • 4
    It sounds like you really want to use pickle, not json. Pickle can write arbitrary Python class objects, which json cannot. json only knows about standard Python objects like integers, floats, booleans, strings, lists, and dicts. – John Gordon Mar 05 '20 at 19:07
  • 1
    And your example isn't writing json anyway; it's just writing a plain text file. – John Gordon Mar 05 '20 at 19:08
  • See my answer to [Making object JSON serializable with regular encoder](https://stackoverflow.com/questions/18478287/making-object-json-serializable-with-regular-encoder). – martineau Mar 05 '20 at 19:16
  • I aggree with @JohnGordon. Pickle will let you serialize anything you want, save to your file and, when you want, unserialize it to the original data. – Dautomne_ Mar 05 '20 at 19:20
  • Ok, thank you everyone. I think I'll try using pickle then. @JohnGordon I had tried using JSON and failed spectacularly, so just attached the normal txt. – Destaq Mar 05 '20 at 19:23

0 Answers0