2011-11-20 47 views
0

我想写使用Python 3Python中打开文件,并在单独的行把名单

我不得不打开一个文本文件,并宣读的名单,打印列表python程序,排序按字母顺序列表,然后重新打印列表。 还有一点比它强,但我遇到的问题是,我应该在单独的行上打印每个名称的名称列表

而不是在单独的行上打印每个名称,它会打印该列表全部在一行上。 我该如何解决这个问题?

def main(): 

     #create control loop 
     keep_going = 'y' 

     #Open name file 
     name_file = open('names.txt', 'r') 

     names = name_file.readlines() 

     name_file.close() 

     #Open outfile 
     outfile = open('sorted_names.txt', 'w') 

     index = 0 
     while index < len(names): 
      names[index] = names[index].rstrip('\n') 
      index += 1 

     #sort names 
     print('original order:', names) 
     names.sort() 
     print('sorted order:', names) 

     #write names to outfile 
     for item in names: 
      outfile.write(item + '\n') 
     #close outfile 
     outfile.close() 

     #search names 
     while keep_going == 'y' or keep_going == 'Y': 

      search = input('Enter a name to search: ') 

      if search in names: 
       print(search, 'was found in the list.') 
       keep_going = input('Would you like to do another search Y for yes: ') 
      else: 
       print(search, 'was not found.') 

       keep_going = input('Would you like to do another search Y for yes: ') 



    main() 
+0

怪蛇4 ??????? – juliomalegria

+0

我不好意思。我正在使用Wing IDE 101 4.1,我把它搞砸了。 –

回答

2

问题是在这里:print('original order:', names)。这是将所有列表打印在一行中。所以不要打印列表中的每个元素在新行,你必须做一些事情,如:

print('original order:') 
for name in names: 
    print(name) 
names.sort() 
print('sorted order:') 
for name in names: 
    print(name) 
+0

谢谢!!!!!! –

+0

@julio:'print'是Python 3中的一个函数。请考虑编辑您的答案,包括删除'pythonic'。如果印刷声明被认为是“pythonic”,它就不会被改变。 –

+0

@John,你是对的,我在Python 2中思考。*,**但是**,只是你知道,Python 3. *不是Python 2的修正。*,只是另一个_branch_,所以我实际上不要以为印刷作为一种陈述更加'pythonic'。 – juliomalegria