Lukali
Lukali

Reputation: 343

How to close a file inside another function of the class in Python?

I got a function run(self) and inside that function I was to open a file. I then want to close that file inside another function, reset(self).

This is my class:

class Heater (threading.Thread):
    STATE_IDLE = "IDLE"
    STATE_RUNNING = "RUNNING"

    def __init__(self, simulate=False, time_step=config.sensor_time_wait):
        threading.Thread.__init__(self)
        self.daemon = True
        self.simulate = simulate
        self.time_step = time_step
        self.reset()
        if simulate:
            self.temp_sensor = TempSensorSimulate(self, 0.5, self.time_step)
        if sensor_available:
            self.temp_sensor = TempSensorReal(self.time_step)
        else:
            self.temp_sensor = TempSensorSimulate(self,
                                                  self.time_step,
                                                  self.time_step)
        self.temp_sensor.start()
        self.start()

    def reset(self):
        self.profile = None
        self.start_time = 0
        self.runtime = 0
        self.totaltime = 0
        self.target = 0

    def run(self):
        now = datetime.datetime.now()
        self.name = os.path.join('/storedata/store', "Date_" + now.strftime("%Y-%m-%d") + ".txt")
        self.file = open(name, 'a')
        self.file.write(now.strftime("%Y-%m-%d"))
        reset()

would I just put self.file = self.run.file.close in reset(self) to achieve this?

Upvotes: 0

Views: 976

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140178

I would do the following:

def __init__(self, simulate=False, time_step=config.sensor_time_wait):
    self.file = None

now there is an attribute called file in your class. Set to None. Now

def __reset(self):
   if self.file:
     self.file.close()
     self.file = None

that should do it ! Note that __reset is safe to call when the file isn't opened, since the file attribute exists and is None (closing an already closed file doesn't do anything, but still, it's clearer)

Note that this design only is interesting if you're using self.file somewhere else. Else don't define any member just do:

name = os.path.join(... // your code used "self.name" for some reason
with open(name, 'a') as file:
    file.write(now.strftime("%Y-%m-%d"))

As a general rule, define class members only when necessary, and local variables anywhere else.

Upvotes: 1

Related Questions