This article mainly introduces python's information about real-time log file traversal. For more information, see open traversal of a large log file.
Use readlines () or readline ()?
In general, readlines () is not slower than python calling readline () again and again, because the loop of the former is at the C language level, and the loop of using readline () is at the Python language level.
But readlines () will read all the data into the memory at a time, and the memory usage will be too high. readline () needs to make a trade-off for reading large files each time it reads only one row.
If you do not need to use seek () to locate the offset, The for line in open ('file') speed is better.
Readlines () is suitable for log files with a small magnitude.
Import osimport timedef check (): p = while True: f = open ("log.txt", "r +") f = open ("result.txt", "a +") f. seek (p,) # readlines () method filelist = f. readlines () if filelist: for line in filelist: # operate the row content f. write (line) # Get the current position and offset p = f for the next while loop. tell () print 'now P', pf. close () f. close () time. sleep () if _ name _ = '_ main _': check ()
Use readline () to avoid excessive memory usage
Import osimport timedef check (): p = while True: f = open ("log.txt", "r +") f = open ("result.txt", "a +") f. seek (p,) # while readline () method while True: l = f. readline () # Empty rows are also true if l: # operate on the row content f. write (l) else: # Get the current position as the offset value p = f. tell () f. close () f. close () breakprint 'now P', ptime. sleep () if _ name _ = '_ main _': check ()