본문 바로가기

IT칼럼/ETC

Python 파일 내 키워드 찾아서 라인 출력하기

 

# file read
searchfile = open("file.txt", "r")  

# line search
for
line in searchfile:
# if 499 is contained in this line

    if "499" in line: print line

searchfile.close()

 ==> main function을 넣어 좀 보기 좋게 만들기

def main():
    searchfile = open("file.txt", "r")
    for line in searchfile:
        if "499" in line:
            print line
    searchfile.close()

if __name__ == "__main__":
    main()

 

멀티플 라인 출력

f = open("file.txt", "r")

searchlines = f.readlines()

f.close()

for i, line in enumerate(searchlines):

    if "499" in line: 

        for l in searchlines[i:i+3]: print l,

        print

 

 

with open("file.txt", "r") as f:

    searchlines = f.readlines()

for i, line in enumerate(searchlines):

    if "499" in line: 

        for l in searchlines[i:i+3]: print l,

        print

 

 

with open('file.txt', 'r') as searchfile:

    for line in searchfile:

        if '499' in line:

            print line

'IT칼럼 > ETC' 카테고리의 다른 글

PostgreSQL column 추가 (Alter table)  (0) 2019.04.09
crontab 사용법  (0) 2019.04.04
jQuery table row add/delete  (0) 2019.03.06
Vi Editor Command (VI 에디터 명령어 모음)  (0) 2019.03.06
Install htop-osx on Mac OSX  (0) 2019.03.02