Python Linecache Module

Source: Internet
Author: User

Linecache

Share a small Python module today: Linecache, which makes it easy to get the contents of a single line of a file. And it is also used by the Traceback module to obtain relevant source information to display.
The usage is simple:

>>> Import linecache>>> linecache.getline ('/etc/passwd ', 4) ' sys:x:3:3:sys:/dev:/bin/sh\n '

Linecache.getline The first parameter is the file name, and the second parameter is the row number. If the file name cannot be found directly, it will be found in the Sys.path.

If the number of rows requested exceeds the number of file lines, the function does not error, but returns an empty string. If the file does not exist, the function does not error and returns an empty string.

Linecache will try to optimize the reading of the file by caching some information. It also provides two ways to handle cache correlation.

Linecache.clearcache ()   # clears Linecache.getcache () that is no longer needed () gets the content Linecache.checkcache ([filename])  # Check that the file is updated on the hard disk if there is an update cache.                                  # If no filename argument is provided, check all entries in the Linecache cache

Other

When a file is large and only one row is read, if you use Linecache as a bottleneck for your program, you can also use the following method to get some speed improvements:

def get_line (Thefilepath, desired_line_number):    if Desired_line_number < 1:return "for    Current_line_ Number, line in enumerate (open (Thefilepath, ' RU ')):        if Current_line_number = = desired_line_number-1:            return Line    return '

PS: The way to open the file ' RU ' is opened in a Windows,mac,unix three platform in the same way, all read into n

  • 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.