简体   繁体   中英

Hello, I am new to python and I am having difficulties on having a file as an input. Can somebody help me please?

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

How can I have the file as an input that i can choose what file to count?

Simplest way would be to:

fileName = sys.argv[1]

you then call the script like so:

python myscript.py myfile.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM