您好,我是python的新手,我在将文件作为输入时遇到困难。有人可以帮帮我吗?

时间:2014-09-26 23:21:10

标签: python

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()

如何将文件作为输入,我可以选择要计算的文件?

1 个答案:

答案 0 :(得分:2)

最简单的方法是:

fileName = sys.argv[1]

然后你这样调用脚本:

python myscript.py myfile.txt