상세 컨텐츠

본문 제목

파이썬 응용 실습2(JsonArray 데이터를 읽고, 쓰기)

기타정보

by 김일국 2022. 7. 4. 10:31

본문

파이썬프로그램 응용 보수교육에서 실습한 내용에서 추가로 작업해 보았다.(아래)

지난 포스트에서 실습한 순서3의 최종결과를 외부 json 파일로 저장하고, 불러오는 기능을 추가한 소스 이다.

friends_list_io.py
0.00MB

- 기존소스에서 외부 json 파일을 def f_load(): 읽어 들이고, def f_save(): 저장하는 함수를 추가하였다.

- 외부 데이터베이스(DB)와 연동하기 바로 전 단계 작업이다. DB연동은 이번 강의에는 없다.

- 실행 결과(아래)

- 소스는 아래와 같다.

import json
menu = 0
friends = []
##외부 파일로 json 데이터 관리  미션 시작
def f_load():
    global friends #전역변수로 사용
    try:
        jsonFile = open('friends.json', 'r', encoding='utf-8')
        #jsonDatas = jsonFile.readlines() 일반 문자열로 읽기
        jsonData = json.load(jsonFile) #json데이터로 읽기
        jsonFile.close()
        #print(type(jsonData))
        friends = jsonData
    except:#FileNotFoundError
        friends = []
    return friends
def f_save():
    #outfile=open('friends.json','w',encoding='utf-8')
    #outfile.writelines(str(friends)) 일반 문자열로 저장
    #outfile.close()
    #아래에서는 딕셔너리를 json string으로 변환해주는 json.dumps를 사용합니다.
    #그리고 ensure_ascii=True는 이스케이프 역슬래시 문자인 유니코드를 한글도 표시
    with open('friends.json', 'w', encoding='utf-8') as outfile:
        json.dump(friends, outfile, ensure_ascii=False, indent=4)#json 저장
#외부 파일로 json 데이터 관리 미션 끝

def f_display():
    #print(f_load())
    friends = f_load()
    print('이름        전화번호')
    print("--------------------")
    if len(friends) == 0:
        print('등록된 회원이 없습니다.')
    for friend in friends:
        print(friend['name'],'    ',friend['phone'])

def f_menu():
    print("--------------------")
    print("1. 친구 리스트 출력")
    print("2. 친구추가")
    print("3. 친구삭제")
    print("4. 이름->전화번호변경")
    print("9. 종료")
    print("--------------------")
    while True:
        try:
            menu = int(input("메뉴를 선택하시오: "))
            break
        except ValueError:
            print("입력값이 숫자가 아닙니다.")
    return menu

def f_input():
    friend = {}
    name = input("이름을 입력하시오: ")
    #friends.append(name)
    phone = input("전화번호를 입력하세요: ")
    friend['name'] = name
    friend['phone'] = phone
    friends.append(friend)
    #파일로 저장
    f_save()

def f_modify():
    old_name = input("변경하고 싶은 이름을 입력하시오: ")
    count = 0
    for index in range(len(friends)):
        if old_name in friends[index]['name']:
            #index = friends.index(old_name)
            #new_name = input("새로운 이름을 입력하시오: ")
            #friends[index] = new_name
            new_phone = input("새로운 전화번호를 입력하시오: ")
            friends[index]['phone'] = new_phone
            count = 1
            f_save()
            break
        #else:
    if count == 0:
        print("이름이 발견되지 않았음")

def f_delete():
    friend = {}
    del_name = input("삭제하고 싶은 이름을 입력하시오:  ")
    count = 0
    for index in range(len(friends)):
        if del_name in friends[index]['name']:
            friends.pop(index)
            count = 1
            f_save()
            break
            #friends.remove(del_name) 
        #else:
    if count == 0:
        print("이름이 발견되지 않았음")

while True: #menu != 9
    menu = f_menu();
    if menu == 1:
        f_display();
    elif  menu== 2:
        f_input()
    elif  menu == 3:
        f_delete()
    elif  menu == 4:
        f_modify()
    elif menu == 9:
        break

 

Ps. 참고로, 파이썬은 자바 프로그램과 비슷하기도 하지만, 다른 점도 있었다.

- 1) 파이썬은 클래스 생성자가 __init__(self) 로 고정되었다. 여기서 self 는 자바의 this 키워드와 같다.

- 2) 자바에서 상속한 @Override의 toString메서드와 비슷한 __str__(self) 처럼 미리 등록된 오버라이드 메서드를 사용가능하다.

- 3) 자바처럼 private 키워드가 아닌 __변수명 으로 비공개 속성(캡슐화)를 구현한다. get(), set() 메서드로 데이터에 접근하는 것은 같다.

-4) 자바의 클래스(멤버)변수와 파이썬의 인스턴스(객체) 변수와 같은 개념이고, 파이썬은 클래스(멤버)변수는 전역변수로 사용된다. 파이썬의 전역변수는 사용시 global 변수명 처럼 키워드를 앞에 붙여야 제대로 동작한다.

- 5) 자바에서는 객체 비교시 == 연산자를 사용하지만(데이터비교:equal메서드사용), 파이썬에서는 == 연산자는 데이터 비교에(객체비교: 객체1 is 객체2) 사용된다.

- 6) 자바에서는 null을 비교로 객체가 비었는지 확인, 파이썬에서는 None 으로 비교 객체가 비었는지 확인한다.

이번에 위 소스를 만들면서 확인한 내용이다.

관련글 더보기

댓글 영역