-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathcount_string_in_file.py
More file actions
29 lines (24 loc) · 981 Bytes
/
count_string_in_file.py
File metadata and controls
29 lines (24 loc) · 981 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
################################################################################
#
# Program: Count The Occurrences Of A String In A File
#
# Description: Program to count the occurrences of a string in a file using
# Python.
#
# YouTube Lesson: https://www.youtube.com/watch?v=QqCmA_T62Mc
#
# Author: Kevin Browne @ https://portfoliocourses.com
#
################################################################################
# Prompt the user for the filename of the file to open and the text string to
# count the occurrences of in that file
filename = input("Filename: ")
text = input("Text: ")
# Open the file with the provided filename for read access
with open(filename) as file:
# Read all the contents of the file, store them into contents
contents = file.read()
# Count the occurrences of the string text in the file contents
text_count = contents.count(text)
# Output the occurrences of the string in the file
print("Count:", text_count)