Python - How can I open a file and specify the offset in bytes?

前端 未结 8 1692
我在风中等你
我在风中等你 2020-12-17 14:37

I\'m writing a program that will parse an Apache log file periodically to log it\'s visitors, bandwidth usage, etc..

The problem is, I don\'t want to open the log an

8条回答
  •  情书的邮戳
    2020-12-17 15:38

    If your logfiles fit easily in memory (this is, you have a reasonable rotation policy) you can easily do something like:

    log_lines = open('logfile','r').readlines()
    last_line = get_last_lineprocessed() #From some persistent storage
    last_line = parse_log(log_lines[last_line:])
    store_last_lineprocessed(last_line)
    

    If you cannot do this, you can use something like (see accepted answer's use of seek and tell, in case you need to do it with them) Get last n lines of a file with Python, similar to tail

提交回复
热议问题