0

I'm currently working on a simple Python 3.4.3 and Tkinter game.

I struggle with saving/reading data now, because I'm a beginner at coding.

What I do now is use .txt files to store my data, but I find this extremely counter-intuitive, as saving/reading more than one line of data requires of me to have additional code to catch any newlines.

Skipping a line would be terrible too.

I've googled it, but I either find .txt save/file options or way too complex ones for saving large-scale data.

I only need to save some strings right now and be able to access them (if possible) by key like in a dictionary key:value .

Do you know of any file format/method to help me accomplish that?

Also: If possible, should work on Win/iOS/Linux.

2 Answers 2

2

It sounds like using json would be best for this, which comes as part of the Python Standard library in Python-2.6+

import json

data = {'username':'John', 'health':98, 'weapon':'warhammer'}

# serialize the data to user-data.txt
with open('user-data.txt', 'w') as fobj:
    json.dump(data, fobj)

# read the data back in
with open('user-data.txt', 'r') as fobj:
    data = json.load(fobj)

print(data)
# outputs: 
# {u'username': u'John', u'weapon': u'warhammer', u'health': 98}

A popular alternative is yaml, which is actually a superset of json and produces slightly more human readable results.

Sign up to request clarification or add additional context in comments.

4 Comments

It seems to be a good solution, unfortunately when I run the first half of your code, it throws a TypeError: 'str' does not support the buffer interface
oops, yeah sorry the 'binary' mode causes issues in python-3 because it's expecting strings to be properly encoded. The fix is to remove the b. Will update the answer
@xXthruXx, should work now in python3, can you give it another try?
Works like a charm :) Thanks!
0

You might want to try Redis.

http://redis.io/

I'm not totally sure it'll meet all your needs, but it would probably be better than a flat file.

2 Comments

You're not sure if Redis would meet all of OP's needs? I would say Redis is waay overkill for this.
I've looked through this and it's a sweet tool, but for this project it's too much compared to other, built-in options. Thanks anyway! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.