Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open file inside class

I have a noob question. I need to do the class, which in init opening file and other function just appending to this opened file text. How I can do this? Need to do something like this, but this is not working, so help.

file1.py

from logsystem import LogginSystem as logsys

file_location='/tmp/test'
file = logsys(file_location)
file.write('some message')

file2.py

class LogginSystem(object):

    def __init__(self, file_location):
        self.log_file = open(file_location, 'a+')

    def write(self, message):
        self.log_file.write(message)

Thanks

like image 626
Manish Iarhovich Avatar asked Jun 30 '26 17:06

Manish Iarhovich


1 Answers

Like zwer already mentioned, you could use the __del__() method to achieve this behaviour.

__del__ is the Python equivalent of a destructor, and is called when the object is garbage collected. It is not guaranteed though that the object will actually be garbage collected (this is implementation dependent)!

Another, more safe approach would be the use of the __enter__ and __exit__ methods which can be implemented in the following way:

class LogginSystem(object):

def __enter__(self, file_location):
    self.log_file = open(file_location, 'a+')
    return self

def write(self, message):
    self.log_file.write(message)

def __exit__(self):
    self.log_file.close()

This allows you to use the with-statement for automatic cleanup:

from logsystem import LogginSystem as logsys

file_location='/tmp/test'
with logsys(file_location) as file:
    file.write('some message')

You can read more about these methods, and the with-statement here


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!