Python File Program Count Characters in Text File

By | August 14, 2019

Task: Write a Python File Program To Count Characters in Text File. This Python Programming tutorial will explain a simple logic to show number of characters in a text file. The Python programming language provides open() function. We will use open() function to open an existing file in read mode.

Python File Program Count Characters in Text File

Python File Programming to find number of  Characters in Text File

As we know that the name of the text file is mytext.txt and it resides on D drive, according to the given question.

We will use another function read() to read all the contents of this text file and store them in a string variable ‘str1’. The len() function will calculate the number of characters in this string. Sine the string contains all data from the text file, so length of string will give the length of file data as well.

Assume that mytext.txt file has the following contents without quotes:

“This file contains some example text.”

The Source code of Python File Program To Count Characters

# Write a python program to
# open a file in read mode
# and count number of characters
# in this text file
# Assume that the text file has the name
# mytext.txt and is on D drive
# Assume that mytext.txt file has the 
# following contents without hash sign

# This file contains some example text.

# open file in read mode
file1 = open("d:/mytext.txt", "r")

# read all the contents of file
# and store in a string variable 
# named str1 using read() function

str1 = file1.read()

# find the length of the string str1
# This will give the length of file
# that is number of characters in this file

char_count = len(str1)

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


# The output is as follows
# The Number of characters in text file : 37

The output will be:
The Number of characters in text file : 37

The Python program wwithout comments

file1 = open("d:/mytext.txt", "r")

char_count = len(str1)

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

str1 = file1.read()

char_count = len(str1)

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

You may also like to read:

Python File Programs – Python File Handling

Write a Python file program read numbers write squares.
Python Text File Read and Show Contents Program
Python Text File Read and Display file data with Exception Handling FileNotFoundError
Python File Program Count Characters in Text File
Python Text File Program To Count Vowels

Loading

One thought on “Python File Program Count Characters in Text File

  1. Pingback: Python file program read numbers write squares | EasyCodeBook.com

Leave a Reply

Your email address will not be published. Required fields are marked *