【问题标题】:Seek to the end of file and go up one line查找到文件末尾并上升一行
【发布时间】:2022-07-22 14:53:11
【问题描述】:

在以下代码中向上导航一行时寻求帮助。 我想不出办法让它上移一条线。

我尝试了 [1] 和 -1,但似乎无法向上移动一行。

感谢任何帮助。我的谷歌技能现在让我失望了。我想我已经盯着这个问题太久了。

 import csv
 import time
 import os
 import datetime as dt
 import sqlite3

def follow(thefile):

    #Seeks to the end of the file 
    thefile.seek(0, os.SEEK_END)  
    
    #Starts an infinte loop
    while True:
        
        #reads the last line of the file
        line = thefile.readline()
        
        #sleep if the file hasn't been updated
        if not line: #sleep if the file hasn't been updated
            time.sleep(0.1)
            continue
        # Once all lines are read this just returns ''
        # until the file changes and a new line appears
        yield line

我关注的文件总是在末尾打印一个空行。

我正在跟踪的示例文件

 10:21:25 service Execution 
 10:22:25 anotherService Execution 
 "<Blank Line>"

我正在更新的示例文件

 10:21:25 service Execution 
 10:22:25 anotherService Execution 
 11:30:00 service execution
 "<Blank Line>"

我正在读取日志文件的软件写入更新的空白行。当软件循环时,它会跳过该行,因为它会滚动到底部,所以我错过了该数据。我想从一行开始阅读。

我想读“11:30:00 服务执行”行

目前,我的代码一直在读取空白行。

【问题讨论】:

  • 任何真正的软件都会遇到写空行的麻烦,然后再寻找并覆盖它,这似乎很不可信。一方面,日志记录功能应该尽可能简单和可预测。我的预感是,您正在使用一种以某种方式欺骗您的工具检查文件。

标签: python logging tail seek


【解决方案1】:

如果我理解你的问题,你需要在有空行时继续while循环,所以只需添加:

if line == '"<Blank Line>"':
    continue

【讨论】:

  • 我认为我的沟通技巧有所欠缺。我正在读取日志文件的软件写入更新的空白行。当软件循环时,它会跳过该行,所以我错过了该数据。我想从一个阵容开始阅读。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 2016-04-04
  • 2020-08-23
  • 2012-05-06
  • 2017-10-14
  • 1970-01-01
相关资源
最近更新 更多