等待文本文件被写入,读取逐行更改并打印

时间:2014-02-12 16:35:50

标签: python file readlines

我有下面的代码,等待一个日志文件出现,它被外部程序保存在那里,当日志文件出现时我打开它,当它仍然被写入,并打印内容,如外部程序正在更新日志文件我要打印出写入它的任何新行。目前我清除打印出来并重新打印整个文本,我想避免,我想只打印新行。另一件需要改进的事情是等待文件出现,而不是仅仅暂停python脚本。

    a=0
    while a <= 10:
        if os.path.isfile(logPath):
            infile = file(logPath)
            break
        a=a+1
        time.sleep(1)
    fileSize1 = 0
    while True:
        wx.Yield()
        fileSize = os.path.getsize(logPath)
        if fileSize > fileSize1:
            lines = infile.readlines()
            log.Clear()
            log.Refresh()
            for line in lines:
                print line.rstrip()
            if "DBG-X: Returning 1" in line:
                break
            if "DBG-X: Returning 0" in line:
                break
        fileSize1 = fileSize
        infile.seek(0)

1 个答案:

答案 0 :(得分:0)

尝试这样的事情......

lastSize = 0
lastLineIndex = 0
while True:
    wx.Yield()
    fileSize = os.path.getsize(logPath)
    if fileSize > lastSize:
        lines = infile.readlines()
        newLines = 0
        for line in lines[lastLineIndex:]:
            newLines += 1
            print line.rstrip()
        lastLineIndex += newLines

        if "DBG-X: Returning 1" in line:
            break
        if "DBG-X: Returning 0" in line:
            break
    fileSize1 = fileSize
    infile.seek(0)

关键位是

for line in lines[lastLineIndex:]:

我们跳过我们已经看过的线。您可以跳过newLines变量,然后执行lastLineIndex += 1但我厌恶改变for循环中的lastLineIndex(这是我为了避免其他问题而选择的习惯语言)