[英]Python save output line into new file
I get some lines (a record) from log file, but I didn't know how to write function inside it to create a new log file whose name contains the current date in which to store those lines. 我从日志文件中得到了一些行(一条记录),但是我不知道如何在其中写入函数来创建一个新的日志文件,该文件的名称包含存储这些行的当前日期。 I'm new python, so I hope you can give me solution.
我是新来的python,所以希望您能给我解决方案。 Thanks
谢谢
def OnlyRecent(line):
if time.strptime(line.split("[")[0].strip(),"%a %b %d %H:%M:%S %Y")> time.gmtime(time.time()-(60*60*24*7)):
return True
return False
for line in f:
if OnlyRecent(line):
print line //store print lines into new log file. 20120911.log
You can redirect print output to a file: 您可以将打印输出重定向到文件:
log_file = open('mylog.log', 'w')
print>>log_file, 'hello'
log_file.close()
outside your loop 在你的循环之外
filename = time.strftime('%Y%m%d') + '.log'
f = open(filename, 'w')
do your loop here, and write each line with 在这里进行循环,并用
f.write(line)
if you don't have a new line character in your line variable, do 如果您的line变量中没有换行符,请执行
f.write(line +'\n')
after exiting your loop 退出循环后
f.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.