0

ファイルに辞書を書き込んだ後、現在、ファイルを正しく表示する際に問題が発生しています。このプログラムでは、入力ファイルは次の形式である必要があります: ID: Date: Dayskept: ProductName eg 1:12/12/2011:12:A

サンプル ファイルを初めて辞書に読み込むときはこれで問題ありませんが、辞書を新しいファイルに保存してこのファイルを開こうとすると、次のような出力が得られます: 1:"date":12/12/2011, "life ":12、"名前":A

ファイルに書き込む前に辞書のデータをフォーマットする簡単な方法はありますか? 与えられたアドバイスに感謝します

    def loadProduct(fileName):
    global cheeseDictionary
    f = open(fileName,"r")
    line = f.readline()         # Reads line from file
    while line:
        line = line[:-1]
        data = split(line,":")  # Splits line when there is a colon
        cheeseDictionary[data[0]] = {"date":data[1], "life":data[2], "name":data[3]} # Stores each split item
        line = f.readline()     # Next line
    f.close()
    print cheeseDictionary

def saveProduct(fileName):
    global cheeseDictionary
    f = open(fileName,"w")
    pickle.dump(cheeseDictionary, f)
    f.close() 
4

1 に答える 1

1

必要な特定の形式があるため、その形式を出力するコードを記述する必要があります。(あなたが何をしようとしているのかわかりません。pickleそれは、あなたが得ていると言っているものとは似ていないバイナリ形式を生成します。)

たとえば、次saveProductのように再定義できます。

def saveProduct(fileName, cheeseDictionary):
    f = open(fileName, "w")
    for i in sorted(cheeseDictionary.keys()):
        v = cheeseDictionary[i]
        f.write("%s:%s:%s:%s\n" % (i, v["date"], v["life"], v["name"]))
于 2011-03-27T21:12:36.737 に答える