Find the number of characters in a file using Python

后端 未结 16 1445
春和景丽
春和景丽 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:27

    Remember that each line (except for the last) has a line separator. I.e. "\r\n" for Windows or "\n" for Linux and Mac.

    Thus, exactly two characters are added in this case, as 47 and not 45.

    A nice way to overcome this could be to use:

    import os
    
    fname=input("enter the name of the file:")
    infile=open(fname, 'r')
    lines=0
    words=0
    characters=0
    for line in infile:
        line = line.strip(os.linesep)
        wordslist=line.split()
        lines=lines+1
        words=words+len(wordslist)
        characters=characters+ len(line)
    print(lines)
    print(words)
    print(characters)
    

提交回复
热议问题