2013-02-28 17 views

回答

1

你不需要readline(); file本身就是一個迭代器。假設單詞之間用空格分隔:

with open(filename) as file: 
    for line in file: 
     words = line.split() 
     if words: 
      # each line in the output has exactly one word in it 
      print("\n".join(words)) 
+0

您的評論不應該是_if行有任何words_,或者_if我們不在空行嗎? – 2013-02-28 05:20:08

+0

使用此語法獲取錯誤,感謝Traceback(最近調用最後一次): 文件「C:/ Documents and Settings/llla/Desktop/Python/c_stuff/c_stuff-primus-try10b.py」,第17行,在 main() 文件「C:/ Documents and Settings/llla/Desktop/Python/c_stuff/c_stuff-primus-try10b.py」,第8行,在主要的 中,打開(gberg.txt)作爲文件: NameError:global名稱'gberg'未定義 >>> – 2013-02-28 05:53:27

+0

@Primus_Pilus:'filename =「gberg.txt」'。爲了避免基本的錯誤,你可以閱讀一些[初學者指南](http://wiki.python.org/moin/BeginnersGuide/NonProgrammers)。 – jfs 2013-02-28 06:19:25

相關問題