在Python程序中,我使用以下内容重定向stdout
:
sys.stdout = open("log_file.txt", "a",0)
在某些条件下,我想重写文件的最后一行。
我在下面尝试过:
if (status=='SAME'):
print '\r'+'Above status doesnot change and last checked @'+str(datetime.datetime.fromtimestamp(time.time())),
当我使用tail命令查看文件时,这似乎有效。
tail -f log_file.txt
然而,当我查看文件的原始内容时,它不会覆盖最后一行,但它会附加。
请建议我保留sys.stdout = open("log_file.txt", "a",0)
的任何其他方法。
我的代码是生成输出:
0007505-160614083053377-oozie-oozi-W-> Started : 2016-06-14 16:15:32
0007505-160614083053377-oozie-oozi-W@HiveScript RUNNING job_1465907358342_1346 RUNNING -
Above status doesnot change and last checked @2016-06-14 16:15:43.096288
Above status doesnot change and last checked @2016-06-14 16:15:53.344065
Above status doesnot change and last checked @2016-06-14 16:16:03.672789
0007505-160614083053377-oozie-oozi-W@end OK - OK -
我希望它是
0007505-160614083053377-oozie-oozi-W-> Started : 2016-06-14 16:15:32
0007505-160614083053377-oozie-oozi-W@HiveScript RUNNING job_1465907358342_1346 RUNNING -
Above status doesnot change and last checked @2016-06-14 16:16:03.672789
0007505-160614083053377-oozie-oozi-W@end OK - OK -
答案 0 :(得分:1)
如果没有实际运行测试用例,我会尝试:
open
append
模式下的文件seek
移回该行的开头write
新文字(确保它至少与原文一样长)。close
文件===================
from __future__ import print_function # for 2.7
f = open('log.txt', mode='r+') # for preexisting file
for i in range(10):
ref = f.tell()
print('%s line %s'%(i,ref), file=f)
if (i % 3)==0:
f.seek(ref)
print('%s oops %s'%(i,ref), file=f)
ref = f.tell()
print('ending at %3d'%100, file=f)
f.seek(ref)
print('ending at %3d'%f.tell(), file=f)
f.close()
产生
2200:~/mypy$ cat log.txt
0 oops 0
1 line 9
2 line 18
3 oops 28
4 line 38
5 line 48
6 oops 58
7 line 68
8 line 78
9 oops 88
ending at 98
在2.7中,这种形式也有效:
sys.stdout = f
for i in range(10):
ref = f.tell() # or ref = sys.stdout.tell()
print '%s line %s'%(i,ref)
if (i % 3)==0:
f.seek(ref)
print '%s oops %s'%(i,ref)
答案 1 :(得分:0)
你可以使用这样的单独的类:
class OverwiteLogger(object):
def __init__(self):
self.filename = "filename.txt"
def write(self, message):
f = open(self.filename, "r")
lines = f.readlines()
lines[-1] = message
open(self.filename, 'w').writelines(lines)
f.close()
并使用它:
logger = OverwriteLogger()
sys.stdout = open('filename.txt', 'a', 0)
if (status=='SAME'):
logger.write('Above status doesnot change and last checked @'+str(datetime.datetime.fromtimestamp(time.time())))
else:
print status
答案 2 :(得分:-1)
我认为你能够做到的唯一方法就是你阅读整个文件并将每一行(最后一行除外)打印回日志。不是非常有效但它应该工作。