Python code output to a file and add timestamp to filename

"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

3

3 Answers

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) 

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 
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() 
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like