2016-03-08 99 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 

此外,您的目标是什么?