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

前端 未结 8 1682
我在风中等你
我在风中等你 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:13

    Here is code proving using the length sugestion of yours and the tell methond:

    beginning="""line1
    line2
    line3"""
    
    end="""- The log will open from this point
    line4
    line5"""
    
    openfile= open('log.txt','w')
    openfile.write(beginning)
    endstarts=openfile.tell()
    openfile.close()
    
    open('log.txt','a').write(end)
    print open('log.txt').read()
    
    print("\nAgain:")
    end2 = open('log.txt','r')
    end2.seek(len(beginning))
    
    print end2.read()  ## wrong by two too little because of magic newlines in Windows
    end2.seek(endstarts)
    
    print "\nOk in Windows also"
    print end2.read()
    end2.close()
    

提交回复
热议问题