How do I watch a file for changes?

前端 未结 25 2807
孤街浪徒
孤街浪徒 2020-11-21 07:13

I have a log file being written by another process which I want to watch for changes. Each time a change occurs I\'d like to read the new data in to do some processing on it

25条回答
  •  死守一世寂寞
    2020-11-21 07:50

    Well, since you are using Python, you can just open a file and keep reading lines from it.

    f = open('file.log')
    

    If the line read is not empty, you process it.

    line = f.readline()
    if line:
        // Do what you want with the line
    

    You may be missing that it is ok to keep calling readline at the EOF. It will just keep returning an empty string in this case. And when something is appended to the log file, the reading will continue from where it stopped, as you need.

    If you are looking for a solution that uses events, or a particular library, please specify this in your question. Otherwise, I think this solution is just fine.

提交回复
热议问题