每次使用Python运行时都有新的文本文件

时间:2015-06-17 08:50:30

标签: python

每次运行以下程序时,如何创建新的文本文件?我想每5秒收集一次数据,但我不想覆盖第一个文本文件。我还使用time.sleep(5)函数。

fobj_out = open("Tabelle.txt", "w")                                 
fobj_out.write("Orte chron.: [Höhe in m, Temp. in °C, rel. Feuchte in %, Niederschlag in mm, Sonnenschein in %]\n")

for key in sorted(unserdictionary.iterkeys()):                      
    print("%s: %s" % (key, unserdictionary[key]))                   
    fobj_out.write("%s: %s\n" % (key, unserdictionary[key]))
fobj_out.close

有简单的方法吗?

3 个答案:

答案 0 :(得分:1)

您可以获取当前时间,并将其附加到文件名。

from time import gmtime, strftime
actual_time = strftime("%Y-%m-%d %H-%M-%S", gmtime())

fobj_out = open("Tabelle - " + str(actual_time) + ".txt", "w")                                 
fobj_out.write("Orte chron.: [Höhe in m, Temp. in °C, rel. Feuchte in %, Niederschlag in mm, Sonnenschein in %]\n")

for key in sorted(unserdictionary.iterkeys()):                      
    print("%s: %s" % (key, unserdictionary[key]))                   
    fobj_out.write("%s: %s\n" % (key, unserdictionary[key]))
fobj_out.close

您将获得如下输出:

Tabelle - 2015-01-01 21-15-13.txt
Tabelle - 2015-01-01 21-20-13.txt

答案 1 :(得分:0)

您可以获取当前时间,然后将其附加到文件名,您可以使用time模块来获取时间。代码就像 -

from time import time 
s = str(round(time() * 1000))
fobj_out = open("Tabelle" + s + ".txt", "w")

答案 2 :(得分:0)

首先检查文件是否已经存在,然后创建它或者只是附加到现有文件。

import os.path

if(os.path.isfile("Tabelle.txt")):
    obj_out = open("Tabelle.txt", "a")   # Append to the file
else:
    obj_out = open("Tabelle.txt", "w")   # create the file

# do the rest here....