Item Counter
Assume that a file containing a series of names (as strings) is named names.txt and exists on the computer’s disk. Write a program that displays the number of names that are stored in the file. (Hint: Open the file and read every string stored in it. Use a variable to keep a count of the number of items that are read from the file.)
Item Counter Python code:
#Create a filename 'names.txt' and file containing
#a series of names (as strings) is named names.txt
filename = "names.txt"
#Displays the number of names that are stored in the file.
try:
with open(filename, 'r') as file:
names = file.readlines()
count = len(names)
print(f"The file '{filename}' contains {count} names.")
except FileNotFoundError:
print(f"File '{filename}' not found.")
except IOError:
print(f"An error occurred while reading the file '{filename}'.")
Data in "names.txt":
John
Peter
Mark
Peter
Josh
Charless
Executed Output:
The file 'names.txt' contains 6 names.