파이썬에서 텍스트 파일에 포함된 문자열 검색
파이썬에서 텍스트 파일을 검색하여 특정 문자열을 찾는 방법입니다. 예시를 보면 금방 알 수 있습니다. 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)
Thank you, friend!


I'm @steem.history, who is steem witness.
Thank you for witnessvoting for me.
please click it!
(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.