2017-05-13 7 views
-1

피클이 어떻게 작동 하는지를 알 수 있도록 코드가 테스트 결과입니다. 사용자가 항목을 추가 할 수있는 단어 목록이 있습니다. 프로그램에 다시 실행될 때 목록에 사용자의 단어가 포함되도록 목록에 단어를 추가하고 싶습니다. 내가 먼저 목록을 정의하기 때문에,이 작업을 수행하는 방법을 이해하지 못하는, 그래서파이썬 3에서 피클을 사용하여 저장 함수를 만드는 방법

import pickle 

    class info(): 
     words = ['skylight','revenue'] 

    item = input("Type a word: ") 
    info.words.append(item) 

    with open("savefile.pickle","wb") as handle: 
     pickle.dump(info.words, handle) 

    with open("savefile.pickle","rb") as handle: 
     info.words = pickle.load(handle) 

    print(info.words) 

답변

0

그럼 원래의 단어 플러스 사용자가 프로그램의 실행에 쓴 단어 결국, 당신이 ' 첫 번째와 두 번째 실행을 구별 할 수있는 방법이 필요합니다. 저장 파일이 있는지 확인하는 것이 좋습니다. 그렇다면 피클을로드 할 수 있습니다. 그렇지 않으면 "기본값"으로 이동합니다.

지금 가지고있는 것, 저장 직후에 피클을로드하고 있습니다. 그것은 말도 안돼.

os.path.isfile을 사용하여 파일이 존재하는지 확인할 수 있습니다.

import pickle 
import os.path 

class info(): 
    words = ['skylight','revenue'] 

if os.path.isfile("savefile.pickle"): 
    with open("savefile.pickle","rb") as handle: 
     info.words = pickle.load(handle) 

item = input("Type a word: ") 
info.words.append(item) 

with open("savefile.pickle","wb") as handle: 
    pickle.dump(info.words, handle) 

print(info.words)