python - 每次在 python 中运行脚本时都需要生成一个新的文本文件并保存它

标签 python python-2.7

我目前有一个程序可以附加到一个名为“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

关于python - 每次在 python 中运行脚本时都需要生成一个新的文本文件并保存它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28708019/

相关文章:

python - 执行程序时出现错误 "NameError: name ' TLSExtSupportedGroup' is not defined"

google-app-engine - 设置 GAE 前端实例类的经验法则

python - 当我运行 .exe 文件时如何停止显示 cmd 提示符

python - 在 Python 中声明简单 PyParsing 递归语法的奇怪警告

python - 通过列表理解展平列表列表

image - 如何验证此 URL 重定向到图像?

html - 无法获取表格数据 - HTML

python - 如何在通过 ruamel.yaml 转储时在 yaml 文件中保留空值

python - 在Python中查找多个重叠矩形的交集区域

python - 如何在 Rasa 中获取最后的用户输入