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
答案 0 :(得分:2)
我相信您要找的是pickle或json图书馆 两者都可以将整个python对象保存到文件中,并在以后加载相同的对象 用法的基本示例:
import pickle
target_object = {some_value:3, other_value:4}
target_file = open("1.txt", "w")
pickle.dump(target_object, target_file)
然后加载:
fl = open("1.txt", "r")
obj = pickle.load(fl)
重要的一点是,正如文档所说,pickle的设计并不安全,因此不要加载用户上传的随机文件等。
但是,腌制文件不易编辑。我发现使用json设置文件更加舒适,因为它们可以通过简单的文本编辑器轻松编辑。这的工作原理大致相同:
json.dump()
转储到文件中,json.load
从文件加载。
但是json不能轻易编码任何对象。它最适合存储dicts
如果您需要更复杂的对象并保持文件可读性,则可以在对象上实现serialize
和deserialize
方法,基本上可以将它们迁移到dict和从dict迁移。这是一个(不完美)的例子:
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']
答案 1 :(得分:0)
您可以使用pickle将完整的对象存储到文件中。
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()