Home >Backend Development >Python Tutorial >Python linecache module
linecache
Today I share a small python module: linecache, which can be used to easily obtain the content of a certain line of a file. And it is also used by the traceback module to obtain relevant source code information for display.
Usage is very 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 line number. If the file name cannot be found directly, it will be found in sys.path.
If the number of requested lines exceeds the number of file lines, the function will not report an error, but will return an empty string. If the file does not exist, the function will not report an error and return an empty string.
linecache will try to cache some information to optimize reading the file. It also provides two methods to handle cache dependencies.
linecache.clearcache() # 清除不再需要的linecache.getcache()获取的内容 linecache.checkcache([filename]) # 检查文件在硬盘上是否有更新,如果有更新缓存。 # 如果没有提供文件名参数,则检查linecache缓存里所有的条目
Others
When the file is very large and only one line is read, if using linecache becomes the bottleneck of the 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 is 'rU' It is opened in the same way on the three platforms of windows, mac and unix, and is read as n