90.8k views
4 votes
Assume a file containing a series of names (as strings) is named names.txt and exists of computer's disk. Write a program that displays the number of names that are stored in the file. While open and read data - check it for the most common exceptions.

User Toote
by
4.2k points

1 Answer

5 votes

Answer:

The program in Python is as follows:

fname = open("names.txt","r")

num = 0

for line in fname:

try:

line = float(line)

except ValueError:

num+=1

fname.close

print(num,"names")

Step-by-step explanation:

This opens the file for read operation

fname = open("names.txt","r")

This initializes the number of names to 0

num = 0

This iterates through the lines of the file

for line in fname:

This runs a value check exception on each name to check for valid strings

try:

line = float(line)

This increases num by 1 for each name read

except ValueError:

num+=1

Close the file

fname.close

Print the number of names read

print(num,"names")

User Chayapol
by
4.7k points