How to count the lines, word, and characters within a text file in Python

Counting the lines, word, and characters within a text file results in the line count, word count, and character count, which includes spaces. For instance the text file containing “Hello World\nHello Again\nGoodbye” results on lines: 3 words: 5 characters: 29

Solution for How to count the lines, word, and characters within a text file in Python : You can use str.split() to count the lines, word, and characters within a text file Call open(file, mode) with the pathname of a file as file and mode as “r” to open the file for reading. Use a for-loop to iterate through the file. At each iteration, use str.strip(characters) with “\n” as characters to strip it from each line str, and use str.split() to create a list containing all the words from the line str. Also, in each iteration, add 1 to the number of lines, use len(object) with the list containing the word from the line as object to add it to the number of words, and use len(object) with the stripped line as object to add it to the number of characters.


how-to-count-the-lines-word-and-characters-within-a-text-file-in-python