SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Tony Gaddis
Chapter:
Files And Exceptions
Exercise:
Programming Exercises
Question:4 | ISBN:9780132576376 | Edition: 2

Question

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.)

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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.

 

0 0

Discussions

Post the discussion to improve the above solution.