2017-10-15 153 views
-2

好吧,所以現在的問題是我只是無法正確加載文件,因爲它應該...當我得到它實際加載它總是隻保留一個值,而不是所有的價值。正確地使這個文件加載正確嗎?(python 2.7)

lista = {'Cop': '911', 'Police chief': '911' 
     , 'firemen' : '912', 'fire chef' : '912' 
     ,} 

保存功能我想它的工作的罰款(得到了我的問題的代碼)

def save(lista): 
    spara = lista 
    from collections import defaultdict 
    d = defaultdict(list) 
    fil = open("test" + ".txt","w") 

    for a, b in lista.items(): 
     d[b].append(a) 

    for a, b in d.items(): 
     fil.write(a+';'+';'.join(b)+"\n") 


    fil.close() 

像下面的負載功能只是想填補了字典'正常',並已全部鍵和值保存到文件之前。

def load(lista): 
     ladda = open("test" + ".txt","r") 
     for namesandnumbers in ladda: 
      (key,val) = namesandnumbers.split(";") 
      lista[(val)] = key[:len(key)] 
      lista = ladda 
      return lista 
while True: 
choice = input(" 1 add to list 2 to save 3 to load ") 
if choice == 1: 
    word = raw_input("Type the key: ") 
    word2 = raw_input("Type the value: ") 
    lista[word] = word2 
    print lista 
    continue 
if choice == 2: 
    save(lista) 
elif choice == 3: 
    load(lista) 
elif choice == 4: 
    False 

在它看起來像這樣

911文件;警察;警察局長;

912; firemen; fire chef;

問題是如何加載時分裂。

+0

改用鹹菜。 https://docs.python.org/2/library/pickle.html – FredMan

+0

@FredMan picke不允許使用。如果是的話就會這樣做。 – noname292123

+0

cat(或以其他方式顯示)我們保存的文件內容,並解釋您得到的錯誤或您使用加載函數獲得的輸出。 – FredMan

回答

0

它看起來像你分裂「;」在負荷,但你在兩個「;」在你的保存功能。

example = "key;;value" 
    example.split(";") 
    ['key', '', 'value'] 

刪除其中的「;」在你的保存功能。

E.G.

fil.write(a+';'+';'.join(b)+"\n") ===== >  fil.write(';'.join((a,b))+"\n") 
+0

是啊,沒有真正做得太多,它試圖保存文件時,代碼崩潰....非常感謝嘗試人。 – noname292123

+0

你收到了什麼錯誤信息?你可以試試+「;」+ b +「\ n」而不是使用str.join()函數。 – FredMan