Python Program to Count Total Number of Characters in a Text File

Q. Write a program to count total number of characters available in a text file in python.

file: text.txt
proram-to-count-total-number-of-words-in-text-file

Solution:

# print total number of characters available in a text file
def read_data():
    f = open("text.txt", 'r')
    s = f.read()
    print(str(len(s))+" "+"Characters")

read_data()

Output:

#282 Characters

count-total-number-of-characters-in-a-text-file

Explanation: Here we have defined a function read_data(). Inside read_data() function we have also created a file object “f” and opened our text file in read mode ie. “r” mode.

In next step, we have initialized all the values to variable “s“. And used read() function to read our file word by word. The read() function return the output in string format.

Note: Here inside function, we have used len() function which returns the total length of object. Here “s” is our file object.

So, now we have the complete text data in string format and we can get the total length of characters by using len() function. Which will return the total length of our text file ie. total number of characters available.

  1. Programming questions on Text Files

    1. WAP to define a method to read text document line by line.
    2. WAP to define a method in python to read lines from a text file starting with an alphabet F.
    3. WAP to define a method to count number of lines starting with an alphabet F.
    4. WAP to define a method which display only those lines starting with an alphabet A or F.
    5. WAP to define a method to display only those lines which are bigger than 50 characters.
    6. WAP to define a method to count total numbers of word available in our text file.
    7. WAP to define a method which counts the occurrence of particular word in a text file.
    8. WAP to define a method which only print the words having more than 5 characters.
    9. WAP to define a method which counts the occurrence of “is”, “to” in a text file.

    Programming questions on Binary Files

    1. WAP to define a method which displays the records of student having marks between 50 & 70.
    2. WAP to define a method which displays only those student records who secured grade A.