我是python的新手,实际上我尝试了一个简单的程序。我正在阅读一个文本文件,它每次都从日志更新数据,所以我需要将该更新的数据仅从该文本文件复制或附加到另一个文本文件并执行一些处理。为此,我完成了下面的代码。
with open("Log.txt") as f:
data = f.readlines()
i=len(data)#find length of file
def check(i):
with open("Log.txt") as f2:
count=f2.readlines()
x=len(count)#finds length of file after update
print(x)
j=i
i=x
while(j<x):
with open("Log.txt") as f1:
count=f1.readlines()
msg=count[j]#get updated text
j=j+1
with open('Output1.txt', 'a') as f3:
f3.write(str(msg))#append updated text to file
process()#calling a function which do some process on text file
while True:
check(i)
通过使用上面的代码我得到更新的数据,但问题是它在进行无限循环时变慢。最初如果我在Log.text文件中有一个数据到12:00 pm它将追加所有数据,在循环之后5分钟后,log.text文件中的数据将会增加,但在相同的5分钟后,我将只获得3分钟的数据到输出文件中。从文本文件中获取数据有很多延迟。为什么我怎么能立即将相同的更新文本输入到输出文件中。
答案 0 :(得分:1)
请尝试以下代码:
def read_and_copy():
with open("/var/log/messages") as input:
with open('/tmp/output', 'a+') as output:
while True:
# read line by line
data = input.readline()
# check if line is not empty
# also if needed - provide necessary checks
if data:
# write to another file
output.write(data)
# Flush the write buffers of the stream if applicable.
# This does nothing for read-only and non-blocking streams.
output.flush()
read_and_copy()
请记住,read_and_copy
的每次调用都会再次读取整个文件并覆盖输出文件。
答案 1 :(得分:0)
我认为你应该使用的是follow
,它跟在文件后面。每当新行添加到Log.txt
时,以下代码会将其更新为Output1.txt
。
试试这个
import os, time
logfile = "Log.txt"
thefile = open(logfile)
def follow(thefile):
thefile.seek(0,2) # Go to the end of the file
while True:
line = thefile.readline()
if not line:
time.sleep(1) # Sleep briefly
else:
with open('Output1.txt', 'a') as f3:
f3.write(line)
loglines = follow(thefile)