Reputation: 73
This seems relevant but I cannot decipher this and apply it to my problem.
Python output file with timestamp
After going through API authorization, I want this website to dump my data every time I call coinbase.py. Here are my relevant lines:
transdata = get_http('https://coinbase.com/api/v1/transfers').read()
f1 = open('./DUMP.txt', 'w+')
f1.write( transdata )
This will overwrite DUMP.txt every time its called. How can I ask python to assign the output file a new name each time this module is calld, conserving the old outputs...and make the name as logical as I can (perhaps with a time and date of the call)?
Upvotes: 1
Views: 779
Reputation: 12077
You can prepend a linux timestamp by using time.time()
and converting the float to an integer:
import time
transdata = get_http('https://coinbase.com/api/v1/transfers').read()
f1 = open('{}_DUMP.txt'.format(int(time.time())), 'w+')
f1.write( transdata )
I'd use the with
-statment so your file is actually handled correctly:
import time
with open("{}_DUMP.txt".format(int(time.time()), 'w+') as out:
out.write(get_http('https://coinbase.com/api/v1/transfers').read())
The time
and datetime
modules provide all you need for handling time on python.
Or if you want a date and time, a quick way to do that is to use datetime.datetime.now()
:
from datetime import datetime
with open("{}_DUMP.txt".format(datetime.datetime.now(), 'w+') as out:
out.write(get_http('https://coinbase.com/api/v1/transfers').read())
Upvotes: 1
Reputation: 44112
Consider using tempfile
https://docs.python.org/2/library/tempfile.html which allows creation of unique file, even with defined name prefix.
But what you describe is usually resolved by dumping the data into one log file, you do not get you directory cluttered with too many files.
Upvotes: 0