Python code output to a file and add timestamp to filename
36,447
Solution 1
If you are following this person's advice (which seems sensible), then this is more of a bash
problem than a Python problem- you can use the date
command to generate the filename within your console command, e.g.:
python /path/to/script/myscript.py > /path/to/output/myfile$(date "+%b_%d_%Y").txt
Solution 2
I did something like this to add the timestamp to my file name.
import time, os, fnmatch, shutil
t = time.localtime()
timestamp = time.strftime('%b-%d-%Y_%H%M', t)
BACKUP_NAME = ("backup-" + timestamp)
Solution 3
import sys
from datetime import datetime
from cStringIO import StringIO
backup = sys.stdout
sys.stdout = StringIO()
run_script();
print 'output stored in stringIO object'
out = sys.stdout.getvalue()
sys.stdout.close()
sys.stdout = backup
filename = '/path/to/output/myfile-%s.txt'%datetime.now().strftime('%Y-%m-%d')
f = open(filename,'w')
f.write(out)
f.close()
Related videos on Youtube
Author by
user3255477
Updated on February 10, 2020Comments
-
user3255477 about 4 years
"I would not even approach this from a python-fix perspective, but simply redirect the output of running your python script: python /path/to/script/myscript.py > /path/to/output/myfile.txt Nothing has to change in your script, and all print statements will end up in your text file."
how can i use the code above to output to a file, but also timestamp the filename? example: python /path/to/script/myscript.py > /path/to/output/myfile01-22-2014.txt
-
Marius over 10 yearsThe person you are quoting is suggesting that you use your shell/command prompt to handle the creation of the file. What shell are you running, e.g. bash or the windows command prompt? Both should have ways of creating timestamps like this fairly simply.
-
user3255477 over 10 yearsi am running bash..... i am new to python, and am using it to get information from a nest thermostat and save it to a file and timestamp it...python /usr/local/bin/nest.py -u alan@###.com -p ####### show > /Users/Alan/Dropbox/NestAPI/CSV-Files/nest.csv
-
jfs about 9 yearsrelated: Redirect stdout to a file in Python?
-
-
user3255477 over 10 yearsthank you for your help, but i am unsure of how to apply this code
-
markcial over 10 yearswith os.popen, but shell option with date parameter seems to be better for your approach, like @Marius said do like this
/path/to/output/file-`date +%Y-%m-%d`.txt
or/path/to/output/file-$(date +%Y-%m-%d).txt