2013-02-17 51 views
0

我已經按照在此線程的第一個答案:將txt導入字典會導致python崩潰?

Python - file to dictionary?

而且每當我嘗試和運行腳本,Python會直接關閉。一切,甚至我的其他腳本,我沒有工作。

這裏就是我有寫的,它幾乎是相同的:

d = {} 
with open("C:\Users\Owatch\Documents\Python\FunStuff\nsed.txt") as f: 
    for line in f: 
     (key, val) = line.split() 
     d[int(key)] = val 

print(d) 

我改變了文件位置作爲唯一的一件事情是什麼,我明白我是爲包括修復有關未找到的錯誤文件

闡述:

這裏是我應該使用的代碼:

d = {} 
with open("file.txt") as f: 
    for line in f: 
     (key, val) = line.split() 
     d[int(key)] = val 

這就是我所做的,添加一個文件路徑代替file.txt,並讓它在應用完成後立即或應該打印字典d。

d = {} 
with open("C:\Users\Owatch\Documents\Python\Unisung Net Send\nsed.txt") as f: 
    for line in f: 
     (key, val) = line.split() 
     d[int(key)] = val 

print(d) 

問題是,我甚至無法運行它,因爲Python會直接崩潰,我正在運行的版本:3.1

+0

能否請您詳細說明。看看你的代碼,看起來你有一個縮進錯誤。 – GodMan 2013-02-17 10:48:32

+0

編輯帖子 – Owatch 2013-02-17 10:54:08

+4

你在Windows上運行這個嗎?如果是這樣,通過'只是崩潰'你的意思是命令窗口再次關閉? – 2013-02-17 10:54:37

回答

1

變化

open("C:\Users\Owatch\Documents\Python\FunStuff\nsed.txt") 

open(r"C:\Users\Owatch\Documents\Python\FunStuff\nsed.txt") 

否則 「\ nsed」 將被視爲一個新行加 「的sed」。

更新:

從輸入文件,問題是:

d[int(key)] = val 

因爲你的第一列是字母,不是整數。將其更改爲:

d[key] = val 

或者:(如果你喜歡數字鍵)

d[ord(key) - ord('a')] = val 
+0

我得到這個錯誤:回溯(最近一次調用最後一次): d:[int(key)] = val 文件「C:\ Users \ Owatch \ Documents \ Python \ FunStuff \ File Import」,第5行,在 ValueError:無效文字爲int()以10爲基數:'a' – Owatch 2013-02-17 11:12:23

+0

好的,應用輸入修正 – Owatch 2013-02-17 11:17:49

+0

固定。謝謝,如果你能幫我多一點,請解釋一下究竟發生了什麼?當我不明白正在進行什麼時,我討厭它。如果你不想,它會很酷。我可能會問一些。感謝您解決問題 – Owatch 2013-02-17 11:19:35

0

使用r''原始字符串字面量,以防止Python從解釋\n作爲一個換行符:

with open(r"C:\Users\Owatch\Documents\Python\Unisung Net Send\nsed.txt") as f: 

或使用雙反斜線:

with open("C:\\Users\\Owatch\\Documents\\Python\\Unisung Net Send\\nsed.txt") as f: 

或正斜槓代替:

with open(r"C:/Users/Owatch/Documents/Python/Unisung Net Send/nsed.txt") as f: 

所有三個版本在Windows上都有效。

+0

我明白,謝謝。 – Owatch 2013-02-17 11:31:32

0

變化d [INT(鍵)到d [ORD(鍵)

+0

使用d [ord(key)]與使用d [key] = val – Owatch 2013-02-17 11:23:29

+0

有什麼不同?如果我希望我的第二列是數字,而不是''中的數字,該怎麼辦? – Owatch 2013-02-17 11:25:18

+0

ord('a')給你97.這個97將被python的字典d中的散列函數所考慮,所以它可以作爲一個鍵 – GodMan 2013-02-17 11:26:00