Python 代码输出到文件并为文件名添加时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21470318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python code output to a file and add timestamp to filename
提问by user3255477
"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."
“我什至不会从 python-fix 的角度来解决这个问题,而是简单地重定向运行 python 脚本的输出: python /path/to/script/myscript.py > /path/to/output/myfile.txt更改您的脚本,所有打印语句都将在您的文本文件中结束。”
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
我怎样才能使用上面的代码输出到一个文件,还要给文件名加上时间戳?示例:python /path/to/script/myscript.py > /path/to/output/myfile01-22-2014.txt
采纳答案by Marius
If you are following this person's advice (which seems sensible), then this is more of a bashproblem than a Python problem- you can use the datecommand to generate the filename within your console command, e.g.:
如果您遵循此人的建议(这似乎是明智的),那么这bash比 Python 问题更重要-您可以使用该date命令在控制台命令中生成文件名,例如:
python /path/to/script/myscript.py > /path/to/output/myfile$(date "+%b_%d_%Y").txt
回答by markcial
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()
回答by Eli
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)

