【问题标题】:Need to generate a new text file and save it every time I run a script in python每次我在python中运行脚本时都需要生成一个新的文本文件并保存它
【发布时间】:2015-02-25 07:55:28
【问题描述】:

我目前有一个附加到一个名为“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 还很陌生,所以如果这听起来像一个愚蠢的问题,我很抱歉)。

【问题讨论】:

  • 如何以w 模式打开文件outFile = open('ConcentrationData.txt','w'),而不是使用像filename = "{0}.{1}".format("Data.txt",timeStr) 这样的文件名常量字符串
  • 如果我将其更改为“w”,我会得到一个具有一个浓度值的文件。如果我将它保持在“a”上,我能够保持我在使用该程序时测量的所有浓度值,而不仅仅是一个。这就是为什么我想创建多个文件,而不仅仅是一个附加每个测量的浓度值的文件。
  • 我建议在程序或实例的整个生命周期内仅打开一次文件,具体取决于您使用w 模式的设计,并在程序结束时关闭它,而不是每次打开和关闭输入函数并像您建议的那样使用不同的文件名使它们独一无二,可能通过添加时间戳filename = "{0}.{1}".format("Data.txt",timeStr) 多次打开和关闭文件也会产生不必要的开销。
  • 你有什么办法可以帮我写这个吗?我明白你在说什么,但我很难把它翻译成代码。所以是
  • 是 measureSample 一个类的实例方法,我在你的定义中看到了一个 self ?

标签: python python-2.7


【解决方案1】:

你可以按照以下几行做一些事情

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

【讨论】: