How can I create a new text file every time I run the following program? I want to collect data, every 5 secs, but I don't want to overwrite the first text file. I use also a time.sleep(5)
function.
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
Is there a simple way?
You can get the current time, and append it to the file name.
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
You will get outputs as follows:
Tabelle - 2015-01-01 21-15-13.txt
Tabelle - 2015-01-01 21-20-13.txt
You can get the current time and then append that to the filename , you can use time
module to get the time. Code would be like -
from time import time
s = str(round(time() * 1000))
fobj_out = open("Tabelle" + s + ".txt", "w")
First check if the file already exists and then either create it or just append to the already existing file.
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....
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.