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