我可以在Python中的析构函数中打开文件吗?

时间:2016-09-09 16:47:46

标签: python

我想做那样的事情:

class DataManager:
    def __init__(self, dirpath):
        self.workdir = dirpath
        self.subjects_list = []
        try:
            self.load()
        except (FileExistsError, FileNotFoundError):
            self.create_base()

    def load(self):
        with open(self.workdir, "rb") as database:
            self.subjects_list = pickle.load(database)

    def save(self):
        with open(self.workdir, "wb") as database:
            pickle.dump(self.subjects_list, database)

    def create_base(self):
        # missed some actions with data
        self.save()

    def __del__(self):
        print("deleted")
        self.save()

datamanager = DataManager("input")

当我运行我的代码时,我收到了这个错误:

Exception ignored in: <bound method DataManager.__del__ 
of <__main__.DataManager object at 0x0050CCF0>>
Traceback (most recent call last):
  File "datamanager.py", line 39, in __del__
  File "datamanager.py", line 20, in save
NameError: name 'open' is not defined

当实例正在销毁时,我无法将当前数据保存到文件中?

编辑:当程序关闭时,如何保存数据? (也许通过互动)

0 个答案:

没有答案