2017-11-26 12 views
1

ユーザーにリストにアイテムを追加するように要求していますが、変更したリストを保存しています。しかし、私がプログラムを再び実行しているとき、以前に追加された要素はなくなりました。なぜ私の新しい要素が一時的に保存されるのか、私のリスト自体がリセットされるのか分かりません。誰かが説明し、私が新しいアイテムを保存する方法をアドバイスできますか?変更されたリストをpickleで保存する問題

import pickle 

my_list = ["a", "b", "c", "d", "e"] 

def add(item): 
    my_list.append(item) 
    with open("my_list.pickle", 'wb') as file: 
     pickle.dump(my_list, file) 
     return my_list 


while True: 
    item = input("Add to the list: \n").upper() 
    if item == "Q": 
     break 
    else: 
     item = add(item) 

with open("my_list.pickle", "rb") as file1: 
    my_items = pickle.load(file1) 

print(my_items) 
+0

「追加」したい場合は、pickleを使用しないでください。pickleとunpickleを処理する必要があります。https://stackoverflow.com/questions/12761991/how-to-use-append- with-pickle-in-python – user1767754

+0

あなたはあなたに入力を求めた後*リストをロードします。 –

答えて

1

あなたはデータでそれを満たした後は、ファイルからリストを読み込みます。私たちは(私はadd機能を削除し、プログラムを注釈付き)、メインを分析するのであれば、我々が得る:

# the standard value of the list 
my_list = ["a", "b", "c", "d", "e"] 

# adding data to the list 
while True: 
    # we write the new list to the file 
    item = input("Add to the list: \n").upper() 
    if item == "Q": 
     break 
    else: 
     item = add(item) 

# loading the list we overrided in this program session 
with open("my_list.pickle", "rb") as file1: 
    my_items = pickle.load(file1) 

# print the loaded list 
print(my_items) 

ですから、デフォルトのリストで始まり、そしてあなたがファイルに要素を追加するたびに書き換えるので、ファイル、あなたがプログラムの最後にリストをロードする場合は、何を推測する?保存したリストを取得します。

溶液は、プログラムの先頭に負荷を移動することである:かなり非効率的である

import pickle 
import os.path 
# the standard value of the list 
my_list = ["a", "b", "c", "d", "e"] 

# in case the file already exists, we use that list 
if os.path.isfile("my_list.pickle"): with open("my_list.pickle", "rb") as file1: my_items = pickle.load(file1) 

# adding data to the list 
while True: 
    # we write the new list to the file 
    item = input("Add to the list: \n").upper() 
    if item == "Q": 
     break 
    else: 
     item = add(item) 

# print the final list 
print(my_items)

注たびに新しいリストを格納します。ユーザーは、リストを変更してプログラムの最後に保存することをお勧めします。

+0

ありがとう! 'os'はいつも必要ですか? – Ank12

+0

@ Ank12:いいえ、ファイルが存在するかどうかを確認する標準的な方法です。 –

関連する問題