python

file - 파일에서 특정 단어를 포함하는 줄만 출력(주소 출력기)

bono.html 2022. 10. 11. 16:48

 

임의의 주소 파일

zipcode.txt
2.29MB

 

파일에서 특정 단어를 포함하는 줄만 출력

readline()은 read()와 다르게 한줄을 출력한다.

한줄 출력한 것을 split()으로 단어 기준으로 쪼개고 리스트에 담는다.

그 리스트의 특정 위치의 단어를 startswith()로 원하는 단어로 시작하는지 확인한다.

if 조건에 맞는다면 형식에 맞춰 출력한다

이것을 while 반복문으로 돌린다.

# 동 이름을 입력해 해당 동 관련 우편번호 및 주소 출력

try:
    dong = input('동 이름 입력: ')
    #print(dong)

    with open('zipcode.txt', mode='r', encoding='euc-kr') as f:
        line = f.readline()
        # print(line)
        while line:
            # split()은 리스트 타입으로 리턴한다
            # lines = line.split('\t')
            # 위의 코드와 같은 뜻, 아스키 코드로 표현
            lines = line.split(chr(9))
            # print(lines)
            if lines[3].startswith(dong):
                # print(lines)
                print('['+lines[0]+']'+lines[1]+' '+lines[2]+' '+lines[3]+' '+lines[4])
            
            line = f.readline()
except Exception as e:
    print('err : ', e)

동 이름 입력: 창동
[132-040]서울 도봉구 창동 
[631-717]경남 창원시 마산합포구 창동 농협마산지부 
[631-090]경남 창원시 마산합포구 창동 
[745-330]경북 문경시 창동