1

I am working on a project that requires variables to be saved in a text file and then turned back into variables. For example, a text file containing

var = "123abc"

would be imported, and the variable and it's contents imported into the code, allowing me to read what the variable var contained. This works great using this code:

def get_save(filename):
result = {}
with open(filename) as f:
    for line in f:
        try:
            line = line.split(' = ',1)
            result[line[0]] = ast.literal_eval(line[1].strip())
        except:
            pass
return result

globals().update(get_save('SAVEFILE.TXT'))

However, I want to do something a little more complex. I would like to be able to create objects within this text file. Here is an example class:

class object():
    def __intit__(self, var, var2):
        self.var = var
        self.var2 = var2

I would then like to be able to do this within my text file:

ob = object("abc", 123)

or:

obs = [object("def", 456), object("ghi", 789)]

and have that imported into my code, ready to be played with. I can think of no way of doing this, any help would be much appreciated!

EDIT: I would like the text file to be easily editable and readable

Thanks

Inazuma
  • 178
  • 3
  • 13

2 Answers2

2

I believe that what you are looking for is the pickle or the json libraries.
Both enable you to save whole python objects to a file, and load the same objects from it later.
A basic example of usage:

import pickle

target_object = {some_value:3, other_value:4}
target_file = open("1.txt", "w")
pickle.dump(target_object, target_file)

And then loading:

fl = open("1.txt", "r")
obj = pickle.load(fl)

An important note is, as the documentation says, pickle is not designed to be secure so don't load random files users upload and such.

However, pickled files are not easily editable. Ive found that using json for settings files is much more comfortable as they can easily be edited by a simple text editor. This works pretty much the same way:

json.dump() dumps into a file, json.load loads from file.

BUT json can not easily encode any object. It is mostly good for storing dicts.
If you DO need a more complex object, and preserve file readability, you can implement serialize and deserialize methods on your objects, basically enabling migrating them to and from a dict. Here's an (imperfect) example:

class SomeObject(object):
    def __init__(self, x, y, data=None):
        if data:
            self.deserialize(data)
        else:
            self.x = x
            self.y = y
    def serialize(self):
        return dict(x=self.x, y=self.y)
    def deserialize(self, data):
        self.x = data['x']
        self.y = data['y']
Arthur.V
  • 676
  • 1
  • 8
  • 22
  • When I try using JSON, I get this error: TypeError: is not JSON serializable – Inazuma Jun 30 '15 at 20:00
  • Yes, I failed to mention it, but json can only serialize basic types, such as a list, dict, Boolean, numbers and so on. serializing an object is a bit more complex, but a solution can be found [here](http://stackoverflow.com/questions/3768895/python-how-to-make-a-class-json-serializable). It all depends on how much complexity you want. If it is just settings files Id recommend saving them as a dict. – Arthur.V Jun 30 '15 at 20:13
0

You can use pickle to store full-blown objects to file.

import pickle

class Holiday():
    def __init__(self):
        self.holiday = True
        self.away = ''

    def set_away(self, holiday):
        if holiday:
            self.away = "Two weeks"

    def say_away(self):
        print(self.away)

obj = Holiday()
obj.set_away(1)

pickle.dump(obj, open('holiday.save', 'wb'))

recovered_obj = pickle.load( open('holiday.save', 'rb'))

recovered_obj.say_away()
stevieb
  • 9,065
  • 3
  • 26
  • 36