Python – Count Number of Characters in Text File

Python – Count Number of Characters

You can count number of words in a text file, by first reading the text to a variable, and then counting the characters. We shall go through the sequence of steps required to count the characters.

Steps to Count Number of Characters

To count the number of characters in a text file, follow these steps.

  1. Open the file in read mode
  2. Read the text using read() function.
  3. Get the length of the string, that should be the number of characters in the text file.
  4. You can refine the count by cleaning the string like removing white space characters and punctuation marks.

Example 1: Count Characters in a Text File

In this Python Example, we will read a text file and count the number of characters in it. Consider the following text file.

Text File

Welcome to www.pythonexamples.org. Here, you will find python programs for all general use cases.

Python Program

#open file in read mode
file = open("C:\data.txt", "r")

#read the content of file
data = file.read()

#get the length of the data
number_of_characters = len(data)

print('Number of characters in text file :', number_of_characters)

Output

Number of characters in text file : 97

Example 2: Count Characters in a Text File excluding spaces

In this Python Example, we will read a text file and count the number of characters in it excluding white space characters. Consider the following text file.

Text File

Welcome to www.pythonexamples.org. Here, you will find python programs for all general use cases.

Python Program

#open file in read mode
file = open("C:\data.txt", "r")

#read the content of file and replace spaces with nothing
data = file.read().replace(" ","")

#get the length of the data
number_of_characters = len(data)

print('Number of characters in text file :', number_of_characters)

Output

Number of characters in text file : 84

Summary

In this tutorial of Python Examples, we learned how to count number of characters in text file, with the help of example programs.