0

Hi I am trying to make a Logfile for my class that anything happens to be written in there...

here is how my class looks like

class MyClass:
    f = open('Log.txt','a')
    def __init__(self):
            self.f = open('Log.txt', 'a')
            self.f.write("My Program Started at "+str(datetime.datetime.now())+"\n")
    def __del__(self):
            self.f.write("closing the log file and terminating...")
            self.f.close()

my code works, but as you see above I have two f=open('Log.txt','a')

is there any way to avoid that ? I tried to delete one of them but it would yell at me... is there any better way to do this?

6
  • 4
    Why does your class have two __init__s? Commented Jun 26, 2013 at 21:47
  • it would yell at me is a vague way to describe a programming problem. Be precise. Please. Commented Jun 26, 2013 at 21:49
  • oops, sorry I it was supposed to be typde del Commented Jun 26, 2013 at 21:49
  • Which one did you delete? Commented Jun 26, 2013 at 21:52
  • we need error messages Commented Jun 26, 2013 at 21:54

2 Answers 2

1

You should have only one.

The first f=... creates the file handler as a class attribute at import time, so the first time you instantiate MyClass you have the handler open, but:

MyClass() # and __del__ is called here
MyClass() # f is closed
ValueError: I/O operation on closed file

If you do it at the __init__ method creates the handler as a instance attribute and opens the file every time you instantiate MyClass(), probably this is what you want, except if you want to use the class without instantiating it.

Sign up to request clarification or add additional context in comments.

Comments

1

What about something like this:

class Test:
  def __init__(self): #open the file
    self.f=open("log.txt", "w") #or "a"
  def mywrite(self, mytext): #write the text you want
    self.f.write("%s\n" % mytext)
  def myclose(self): #close the file when necessary (you don't need to delete the object)
    self.f.close()

myFile=Test()
myFile.mywrite("abcd")
myFile.myclose()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.