2016-03-08 97 views
-3
fn = raw_input("Enter file to open: ") 
fileObject = open(fn,'r+') 
dictionary = {} 
for line in fileObject: 
    x = line.split(":") 
    a = x[0] 
    b = x[1] 
    c = len(b)-1 
    b = b[0:c] 
dictionary[a] = b 
print dictionary 

當我測試了我的程序後,發現除了2個小問題外,一切都很完美。你能告訴我什麼是錯的嗎?兩個小蟒蛇問題

我的文本文件中有以下內容:

USERNAME1:密碼1

USERNAME2:密碼2

USERNAME3:password3

username4:password4

username5:password5

(這是實際的文本文件中的空行)

第一個問題: 我的程序讀取文件轉換成字典完美,但它是閱讀無序,我試圖打印字典中讀入後詞典部分和下面是我得到的。

{'username1': 'password1', 'username3': 'password3', 'username2': 'password2', 'username5': 'password5', 'username4': 'password4'} 

問題二:

爲文本文件,password5後,我不得不按下回車鍵保存文本文件來得到這樣的:

{'username1': 'password1', 'username3': 'password3', 'username2': 'password2', 'username5': 'passwor**d5'**, 'username4': 'password4'} 

,如果我不打進入在文本文件的末尾,那麼它將成爲:

{'username1': 'password1', 'username3': 'password3', 'username2': 'password2', 'username5': 'passwo**rd'**, 'username4': 'password4'} 
+0

Python字典沒有排序。閱讀[this](http://stackoverflow.com/a/15479974/1832539) – idjaw

+0

使用[OrderedDict](https://docs.python.org/2/library/collections.html#collections.OrderedDict)而不是 – mshsayem

+0

首先問題很簡單:字典無法排序。如果你想要一個已排序的字典,你可以使用'collections.OrderedDict' – zondo

回答

0

您正在使用無序字典,即wh在打印字典時,y順序不會被保留。其次,需要換行符才能正確使用for-in循環。

0

你錯了,字典沒有訂購。

我建議使用OrderedDict代替或使用Python列表。

fn = raw_input("Enter file to open: ") 
fileObject = open(fn,'r+') 
list1 = [] 

for line in fileObject: 
    x = line.split(":") 
    list1.append(x) 

print list1 

此外,您的目標是什麼?