Find the number of characters in a file using Python

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

    Here i got smallest program with less memory usage for your problem

    with open('FileName.txt') as f:
      lines = f.readlines()
      data = ''.join(lines)
      print('lines =',len(lines))
      print('Words = ',len(data.split()))
      data = ''.join(data.split())
      print('characters = ',len(data))
    

    lines will be list of lines,so length of lines is nothing but number of lines.Next step data contains a string of your file contents(each word separated by a whitespace), so if we split data gives list of words in your file. thus, length of that list gives number of words. again if we join the words list you will get all characters as a single string. thus length of that gives number of characters.

提交回复
热议问题