[Python] linecache module
2021. 11. 1. 05:57ㆍProgramming/python
Python으로 자동화를 진행하던 중 linecache라는 module이 있다는 것을 알게 되었다.
linecache는 파일을 열어서 특정 줄에 빠르게 access 할 수 있다.
https://github.com/python/cpython/blob/main/Lib/linecache.py
GitHub - python/cpython: The Python programming language
The Python programming language. Contribute to python/cpython development by creating an account on GitHub.
github.com
메뉴얼에는 한줄만 가져오는 linecache.getline(filename,linenumber) 메소드만 나와있는데,
linecache.getlines(filename) 를 이용하면 모든 라인을 list 형태로 가져오게 되고, 이걸 잘라서 여러줄을 한번에 가져올 수도 있다.
사용 방법은 아래와 같다.
import lincache
filename= "file.txt"
linenum=100
line = linecache.getline(filename,linenum)
data= linecache.getlines(filename)[10:20]
위 코드를 실행하면
| hello line10 ['hello line11\n', 'hello line12\n', 'hello line13\n', 'hello line14\n', 'hello line15\n', 'hello line16\n', 'hello line17\n', 'hello line18\n', 'hello line19\n', 'hello line20\n'] |
linecache.getline(filename, linenum ) : filename 에서 linenum 번째 줄을 가져온다.
상용툴의 log들 같은 경우 몇번째 줄에 어떤 로그가 있는지 확실히 알고 있는 경우가 있기도 해서
특정 부분만 parsing 해서 사용할 때 유용하게 사용했다.