11

"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

user3255477
  • 113
  • 1
  • 1
  • 4
  • The 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. – Marius Jan 31 '14 at 00:31
  • i 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 – user3255477 Jan 31 '14 at 01:51
  • related: [Redirect stdout to a file in Python?](http://stackoverflow.com/q/4675728/4279) – jfs Feb 09 '15 at 21:23

3 Answers3

16

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)
Eli
  • 161
  • 1
  • 2
4

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
Marius
  • 58,213
  • 16
  • 107
  • 105
1
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()
markcial
  • 9,041
  • 4
  • 31
  • 41
  • thank you for your help, but i am unsure of how to apply this code – user3255477 Jan 31 '14 at 01:53
  • with 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` – markcial Jan 31 '14 at 06:24