2011-11-20 72 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