In this example we will show how to count the number of times a specified letter appears in a text file.
Source Code
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
fileName = input("Enter the name of the file with .txt extension: ")
letter = input("Please input the letter: ")
with open(fileName, 'r') as file:
contentStr = " ".join(file.readlines())
print('The number of "{}" is: {}'.format(letter, contentStr.count(letter)))
Content of test1.txt:
Python is an easy to learn
powerful programming language
Output:
Enter the name of the file with .txt extension: test1.txt
Please input the letter: a
The number of "a" is: 6