파이썬에서 텍스트 파일에 포함된 문자열 검색

in hive-141029 •  11 months ago 

파이썬에서 텍스트 파일을 검색하여 특정 문자열을 찾는 방법입니다. 예시를 보면 금방 알 수 있습니다. my_file.txt 파일에서 문자열 "abcd"를 찾고 몇번째 행에 있는지 출력하는 경우입니다.

open()으로 파일을 열어서 파일 포인터를 enumerate()에 적용하면, for 반복문을 통해서 행번호와 행을 하나씩 가져올 수 있습니다. 이렇게 가져온 행에 원하는 문자열이 있는지 찾습니다.

f = open('my_file.txt', 'r')

# 문자열 "abcd" 검색
for line_num, line in enumerate(f):
  if 'abcd' in line:
    print(line_num, ':', line.rstrip())

print()로 출력하는 문자열에 대해서는 줄바꿈(\n)이 중복되지 않도록 하기 위해 행에 포함된 줄바꿈을 제거하는 rstrip()을 사용했습니다.


@joviansummer의 스팀 프로젝트

스팀 증인노드를 운영중입니다. @jswit에 증인투표해 주시면 감사하겠습니다.
(https://steemitwallet.com/~witnesses)

jswit 증인 노드 프로젝트를 시작합니다.

jsup 업보팅(upvoting) 서비스 소개

jsup 수혜자 지정 기능 추가

jsup 2.0 - 업보팅을 다시 위대하게

jSTEEM 프로젝트 - 텔레그램 챗봇으로 구현하는 스팀 블럭체인 탐색기

Steemit-Search - 스팀잇 포스팅 검색

STEEM.NFT - 디지털 아트 보존 프로젝트

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Thank you, friend!
I'm @steem.history, who is steem witness.
Thank you for witnessvoting for me.
image.png
please click it!
image.png
(Go to https://steemit.com/~witnesses and type fbslo at the bottom of the page)

The weight is reduced because of the lack of Voting Power. If you vote for me as a witness, you can get my little vote.

Upvoted! Thank you for supporting witness @jswit.