Merging and sorting log files in Python

前端 未结 5 1059
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-02 02:58

I am completely new to python and I have a serious problem which I cannot solve.

I have a few log files with identical structure:

[timestamp] [level]         


        
5条回答
  •  不知归路
    2021-01-02 03:39

    Read the lines of both files into a list (they will now be merged), provide a user defined compare function which converts timestamp to seconds since epoch, call sort with the user defined compare, write lines to merged file...

    def compare_func():
        # comparison code
        pass
    
    
    lst = []
    
    for line in open("file_1.log", "r"):
       lst.append(line)
    
    for line in open("file_2.log", "r"):
       lst.append(line)
    
    # create compare function from timestamp to epoch called compare_func
    
    lst.sort(cmp=compare_func)  # this could be a lambda if it is simple enough
    

    something like that should do it

提交回复
热议问题