Marina Hanna
Marina Hanna

Reputation: 51

Need to generate a new text file and save it every time I run a script in python

I currently have a program that appends to an already existing file called "ConcentrationData.txt". However, I would like to create a new text file every time the program is run, preferably with a file name that has the date and time. This is what my current script looks like:

def measureSample(self):
    sys.stdout.flush()
    freqD1, trandD1, absoD1 = dev.getMeasurement(LED_TO_COLOR='D1'])
    freqD2, trandD2, absoD2 = dev.getMeasurement(LED_TO_COLOR='D2'])
    absoDiff= absoD1 - absoD2
    Coeff= 1 
    Conc = absoDiff/Coeff
    Conc3SD = '{Value:1.{digits}f'.format(Value = Conc, digits=3)
    self.textEdit.clear()
    self.textEdit.setText('Concentration is {0}'.format(Conc3SD))

    timeStr = time.strftime('%m-%d-%Y %H:%M:%S %Z')
    outFile = open('ConcentrationData.txt','a')
    outFile.write('{0} || Concentration: {1}'.format(timeStr, Conc3SD))
    outFile.close()

How would I go about doing that?

(Also, I'm pretty new to python so I'm sorry if this sounds like a silly question).

Upvotes: 2

Views: 2863

Answers (1)

cmidi
cmidi

Reputation: 2020

You can do something on the lines of the following

class my_class:
   _data_fd = None

   def __init__(self,create,filename):
       if(create):
           self._data_fd = open(filename,'w')

   def __del__(self):
       if(self._data_fd != None):
           self._data_fd.close()

   def measureSample(self):
       ##do something here
       outFile = self._data_fd
       outFile.write('{0} || Concentration: {1}'.format(timeStr, Conc3SD))


if __name__ == '__main__':
    timeStr = time.strftime('%m-%d-%Y_%H_%M_%S_%Z') #use unerscore instead of spaces
    filename = "{0}.{1}".format("Data.txt",timeStr)
    imy_class = my_class(1,filename)
    imy_class.measureSample()
    imy_class.measureSample() ##call multiple times the fd remains open for the lifetime of the object
    del imy_class   ### the file closes now and you will have multiple lines of data

Upvotes: 3

Related Questions