简体   繁体   中英

Exporting a dictionary into a text-file

The game is about tamaguchis, and I want the tamaguchi to remember its last size and it's 3 last actions the next time it plays. I also want the date to matter, like if you don't play with it for a week it shrinks in size. So first step I thought was to save down all the relevant data to a text file, and each time the game starts the code searchs through the text file and extracts the relevant data again! But I can't even get step 1 working :( I mean, I don't get why this doesn't work??

file = open("Tamaguchis.txt","w")
date = time.strftime("%c")
dictionary = {"size":tamaguchin.size,"date":date,"order":lista}
file.write(dictionary)

it says that it can't export dictonaries, only strings to a text file. But that's not correct is it, I thought you were supposed to be able to put dictionaries in text files? :o

If anyone also has an idea on how calculate the difference between the current date, and the date saved in the text file, that'd be much appriciated :)

Sorry if noob question, and thanks a lot!

If your dictionary consists only of simple python objects, you can use json module to serialize it and write into a file.

import json
with open("Tamaguchis.txt","w") as file:
    date = time.strftime("%c")
    dictionary = {"size":tamaguchin.size,"date":date,"order":lista}
    file.write(json.dumps(dictionary))

The same can be then read with loads .

import json
with open("Tamaguchis.txt","r") as file:
    dictionary = json.loads(file.read())

If your dictionary may contain more complex objects, you can either define json serializer for them, or use pickle module. Note, that the latter might make it possible to invoke arbitrary code if not used properly.

You need to convert the dict to a string:

file.write(str(dictionary))

... though you might want to use pickle , json or yaml for the task - reading back is easier/safer then.

Oh,, for date and time caculations you might want to check the timedelta module.

import pickle

a = {'a':1, 'b':2}
with open('temp.txt', 'w') as writer:
    data = pickle.dumps(a)
    writer.write(data)

with open('temp.txt', 'r') as reader:
    data2= pickle.loads(reader.read())
    print data2
    print type(data2)

Output:

{'a': 1, 'b': 2}
<type 'dict'>

If you care efficiency, ujson or cPinkle is better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM