Find the number of characters in a file using Python

后端 未结 16 1822
春和景丽
春和景丽 2021-02-07 00:34

Here is the question:

I have a file with these words:

hey how are you
I am fine and you
Yes I am fine

And it is asked to find the numbe

16条回答
  •  我寻月下人不归
    2021-02-07 01:12

    taking the input as file name i.e files.txt from the input parameter and then counting the total number of characters in the file and save to the variable char

    fname = input("Enter the name of the file:")
    infile = open(fname, 'r')                   # connection of the file
    lines = 0
    words = 0
    char = 0                                    # init as zero integer
    for line in infile:
        wordslist = line.split()                # splitting line to word
        lines = lines + 1                       # counter up the word
        words = words + len(wordslist)          # splitting word to charac
        char = char + len(line)                 # counter up the character
    
    print("lines are: " + str(lines))
    print("words are: " + str(words))
    print("chars are: " + str(char))            # printing beautify
    

提交回复
热议问题