A memo when you want to extract only the specified line from the file in the program
linecache Source code: https://hg.python.org/cpython/file/3.4/Lib/linecache.py Reference URL: http://docs.python.jp/3.4/library/linecache.html
The linecache module uses a cache (which typically reads many lines from a single file) to allow you to retrieve arbitrary lines in a Python source file with internal optimization. .. The traceback module makes use of this module to include the source code in a well-formed traceback.
You can read the specified line with linecache.getline (filename, lineno)
. Specify the file name in filename
and the number of lines in lineno
. lineno
is an integer from1 ~
.
The sample.txt
used below is a file that describes the Nth line and each line from the 0th line to the 1000th line. (When I first thought that lineno
started with 0
, it started with 1
, so it started with 0.)
Code created this time: https://github.com/KodairaTomonori/Qiita/tree/master/default_module/linecache
test_linecache.py
import linecache
a = input('How many lines do you want to retrieve? :')
target_line = linecache.getline('sample.txt', int(a))
print(target_line)
linecache.clearcache()
$ head sample.txt
Line 0
The first line
2nd line
3rd line
4th line
5th line
6th line
7th line
8th line
9th line
$ python test_linecache.py
How many lines do you want to retrieve? : 100
Line 99
linecache.getline
returns the string for that specified line.
The last linecache.clearcache ()
uses the cache, as mentioned in the first quoted sentence, so clear it when you no longer use the file.
If the file size is small, I think it is faster to make a list with readlines ()
normally. (Not a speedy story)
Also, if you just want to check the specified line,
head -100 sample.txt | tail -1
You can see it normally at.
Recommended Posts