2016-04-03 6 views
1

でリストを作成します。私は "テーブルメーカー"を作ろうとしています - 辞書とチェックキーでファイルを作成するだけです。は選択して、別の問題で再びループ

私は2つの問題を抱えている:バイナリで書いたが、それがすでに存在する場合、以前のファイルを上書きしないためのファイルフォーマットが存在する場合、まず、私は知らないのですか?私は(してみてください、除く)の方法を試してみましたが、除外FileExistsErrorが出てくることはありませんん:/

(のcreateTable関数の中で)第二に、私はリストを作成して問題を抱えています。私は、それらのエントリと値を別々のリストに格納するよう求めるループを作った。これらのリストは後で辞書に圧縮され、ファイルにまとめられます。もちろん(のcreateTable関数内)

私は彼らを愛したい、他の間違いがある場合は、最初のファイルからリストを読み込むリストに追加酸洗いする必要が指摘:)

import pickle 

def checkTable(nameOfTable) : 

    try : 
     #seeing what is it they are looking for 
     prompt = input("What do you want to check?\n") 
     with open("%s.pkl" % nameOfTable, "rb") as f: 
      data = pickle.load(f) 
      #getting what they want from the data from table 
      whatTheyWant = data.get(prompt, "There is nothing like that in the table.\n") 
      print(whatTheyWant) 
    #if table doesn't exist 
    except IOError as e: 
     print("Sorry such a directory doesn't exist.\n") 


def createTable(nameOfYourTable) : 
    try : 
     #opens a new file with the table 
     with open("%s.pkl" %nameOfYourTable, "wb+") as f : 
      decision = "yes" 
      if decision == "yes" : 
       #asking for entries and keys to put into the table 
       #creates lists with entries and values to be zipped together 
       entry.append = input("What is the entry?\n") 
       value.append = input("What is the value of the entry?\n") 
       decision = input("Do you want to go on? (yes/no)\n") 
       i += 1 
      else : 
      #getting it all into a dictionary and putting it into a file 
       table={dict(zip(entry, value))} 
       pickle.dump(table, f) 
    #if a file with the name already exists 
    except FileExistsError as e : 
     print("Sorry, a file with this name already exists.") 


#what the person wants to do 
answer = input("Hello. Do you want to create a table or check an existing one?\n") 

#asking for the name of the new table 
if answer == "create" : 
    nameOfYourTable = input("What do you want the table to be called?\n") 
    createTable(nameOfYourTable) 
#asking what table to look in 
elif answer == "check" : 
    nameOfTable = input("What is the name of the table?\n") 
    checkTable(nameOfTable) 
else : 
    print("\nThat's not a valid option.\n") 

print("Thank you for using me. It was very nice.") 
+1

あなたは、任意の意味をなさないだろうと、ピクルスを含むファイルにデータを追加することはできません。とにかく、別のファイル形式の使用を検討する必要があります。あなたのdictには文字列だけが含まれているので、JSONのようなテキストのシリアル化形式がはるかに適切です。 –

答えて

0

を、最後に新しいピクルファイルを作成します。 Btwの場合、ファイルがos.path.existsであるかどうかを確認できます。リストに項目を追加するには、list_name.append(new_item)を使用します。最初にリストをlist_name = []で初期化しておく必要があります。

1

あなたの必要性に応じてopen(file, "x")のファイルモードがあり、bまたはtを追加してください。 xモードで

それはがすでに存在しない場合にのみ、ファイルが作成されるが、そうでない場合は例外が発生します。 createTable機能は実際に私には意味をなさない。 decision = "yes"その後、if decision == "yes":decisionglobalことになっていますか?それは非常にあいまいです。