我用Python 3创建了一个程序,使用pickle保存了之前的运行。但我需要使用.txt文件。据我所知,可以使用open和.write命令完成吗?但我不太清楚如何做到这一点。该程序适用于pickle,但我必须学习如何使用文本文件。我非常感谢任何帮助! 这是在每次运行后保存信息的功能模块:
import pickle
class TV(object):
def __init__(self, name):
self.name = name
try:
self.load()
except:
self.Kanal = 1
self.Volym = 1
def __str__(self):
printstring = str("\n".join(("%s:","Kanal: %s", "Volym: %s"))%(self.name, self.Kanal, self.Volym))
return printstring
def bytKanal(self,kanal):
self.Kanal = kanal
self.save()
return kanal
def sank_volym(self):
if self.Volym!=0:
self.Volym -= 1
self.save()
return self.Volym
def hoj_volym(self):
if self.Volym!=10:
self.Volym += 1
self.save()
return self.Volym
def save(self):
file = open(self.name+".txt","wb")
file.write(pickle.dumps(self.__dict__))
file.close()
def load(self):
file = open(self.name+".txt","rb")
datapickle = file.read()
file.close()
self.__dict__=pickle.loads(datapickle)
答案 0 :(得分:2)
由于您只序列化实例 dict ,我建议使用json
def save(self):
with open(self.name+".txt","w") as file:
file.write(json.dumps(self.__dict__)) #json
def load(self):
with open(self.name+".txt","r") as file:
json_data = file.read()
self.__dict__=json.loads(json_data) #json!
您可能还想了解json:https://en.wikipedia.org/wiki/JSON