yeonghoon.kim

  • 게시판
  • 갤러리
  • aws

김영훈

IP 위치 정보 CSV 저장. 위 코드를 리팩토링해줘

 

import geoip2.database

def main():
    with geoip2.database.Reader('GeoLite2-City.mmdb') as reader:
        with open('iplists.txt', 'r') as iplist_file, open('iplist_result.csv', 'w') as output_file:
            for ip in iplist_file:
                ip = ip.strip()
                response = reader.city(ip)
                country_iso_code = response.country.iso_code if response.country else "Unknown"
                output_file.write(f"{country_iso_code},{ip}\n")

if __name__ == "__main__":
    main()
 

이 리팩토링된 코드는 다음과 같은 변경 사항을 포함합니다:

  1. sys.stdout을 사용하는 대신에 파일을 열고 닫는 with 문을 사용하여 출력을 관리합니다.
  2. IP 주소를 읽을 때 불필요한 공백을 제거하여 처리합니다.
  3. 응답에서 국가 정보를 가져올 때, 국가 정보가 없는 경우에 대한 처리를 추가했습니다.

이제 위 코드를 사용하여 원하는 결과를 얻을 수 있을 것입니다.

사진 및 파일 첨부

여기에 파일을 끌어 놓거나 왼쪽의 버튼을 클릭하세요.

파일 용량 제한 : 0MB (허용 확장자 : *.*)

업로드 중... (0%)

0개 첨부 됨 ( / )