'With open inside of a class

Hello I am doing an assignment and I have a similar problem as to here but in this case I am unable to change the file = logsys(file_location) part due to the assignment rules. Is there any way I can do the "with" part inside of the class?

My code is shown below

doc = write("test_2.txt")

class HtmlTable: 

  def __init__(self, filename):
    self.filename = filename
    self.fp = None

  def tag(self, text):

    self.fp.write('<' + text+ '>' +'\n')

  def __iadd__(self, text):

    self.fp.write(text)

  def __enter__(self):   

    self.fp = open(self.filename, "a+")

    return self

  def __exit__(self, exception_type, exception_value, traceback):
    
    self.fp.close()

The idea is that i want to call the class and let it handle the with part for me



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source