2014-09-26 50 views
-1
def main(): 
    lines = 0 
    words = 0 
    chars = 0 
    print("This program will count the number of lines, words, and characters in a file.") 
    with open(filename, 'r') as fileObject: 
     for l in fileObject: 
      wordsfind = l.split() 
      lines += 1 
      words += len(wordsFind) 
      chars += len(l) 
     print("The file thoreau.txt has: ") 
     print("Lines ==>   ", lines) 
     print("Words ==>   ", words) 
     print("Characters ==> ", chars) 

main() 

如何將文件作爲輸入來選擇要計數的文件?你好,我是新來的python,我有困難有一個文件作爲輸入。有人可以幫我嗎?

+0

你好,你有沒有嘗試過的教程?例如,在Python自己的網站上,他們談論[命令行參數](https://docs.python.org/2/tutorial/stdlib.html#command-line-arguments)。 – vanza 2014-09-26 23:28:04

回答

2

簡單的方法是到:

fileName = sys.argv[1] 

你再調用腳本像這樣:

python myscript.py myfile.txt 
相關問題