簡體   English   中英

每次我在python中運行腳本時,都需要生成一個新的文本文件並將其保存

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

我目前有一個程序可以追加到一個已經存在的名為“ ConcentrationData.txt”的文件中。 但是,我想在每次運行程序時創建一個新的文本文件,最好使用具有日期和時間的文件名。 這是我當前的腳本的樣子:

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()

我將如何去做?

(此外,我對python還是很陌生,如果這聽起來像一個愚蠢的問題,我感到抱歉)。

您可以按照以下方式進行操作

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM