사전 저장을 위해 피클을 사용하기 위해 필요한 것
Aug 21 2020
키와 값을 사전에 저장하고 내일 또는 다음 주에 사용하고 싶습니다. "A byte of Python"책을 읽었습니다. 책에서 질문을하고 싶지만 사전으로 작업하는 방법을 이해하지 못합니다.
import os
import pickle
addressbook = {}
home = os.environ['HOME']
path = home + '/.local/share/addressbook'
addressbookfile = path + '/' + 'addressbook.data'
if not os.path.exists(path):
os.mkdir(path)
while True:
print("What to do?: ")
print("1 - full list")
print("2 - add a contact")
print("3 - remove contact")
answer = int(input("Number of answer: "))
if answer == 1:
f = open(addressbookfile, 'rb')
storedlist = pickle.load(f)
print(storedlist)
elif answer == 2:
namecontact = str(input("Enter the name of cantact: "))
name = str(input("Enter the name: "))
lastname = str(input("Enter the lastname: "))
number = int(input("Enter the number: "))
addressbook[namecontact] = [name, lastname, number]
f = open(addressbookfile, 'wb')
pickle.dump(addressbookfile, f)
f.close()
답변
L.S.Harbo Aug 21 2020 at 13:32
Python pickle은 객체를 직렬화하고 deserialises하며 나중에 사용할 수 있도록 변수를 파일에 저장하는 데 사용할 수 있습니다.
당신이 할 때, 변수는
pickle.dump(addressbook , f)
데이터를로드 할 수 있습니다.
addressbook = pickle.load(f)
f는 파일 핸들입니다.