Python traverses log files in real time

Source: Internet
Author: User
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 ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.