Python3: How to save data, when the destructor is called
I actually have a question on Python3. I want to save the attributes of a class in a file, when the destructor is called. How can I do that? I tried to do it like this: def __del__: file = open("test.dat", "w") file.write("Hello") file.close() That code doesn't work. I've already read, that you shouldn't use it, but I actually didn't find a alternative which works. Can anybody help me? Thanks in advance!
to use that code it needs to be part of a class: class Test(): def __init__(self): self.data = "Hello" def __del__(self): with open('text.txt', mode='w') as file: file.write(self.data) if __name__ == '__main__': def something(): obj = Test() # obj is deleted when function exits as it becomes out of scope something() obj = Test() del obj # also works because we explicitly delete the object note that while this method does work, it cannot always be relied upon to always be executed, for example if a sys.exit is called
Python 3.5 csv input shows extra character 'b'
Python Error 104, connection reset by peer
css not getting loaded in flask webpage?
Regarding the regex in search module with and without raw text
How to calculate the mean of a column by decade in Python
How to read webpages that are without .htm* extension using Python?
can I use python's 'socket' module to connect to a wireless ethernet host?
Requests VS Urllib 2 [closed]
Call python class from another Python script
How can I use BeautifulSoup to get a few contents that comes after a specific text on a page?
Reinstall python 2.7.12 and python 3.5.2
How to keep chrome browser window open after selenium script finishes on python
Outlook email attachment downloader (Date range)
Create array based on conditional logic of values in other arrays in Python
Python qt - TableWidget update MySQL
Getting black plots with plt.imshow after multiplying image array by a scalar