Assume that a file containing a series of cities (as strings) is named cities.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.)

Respuesta :

Answer:

name = 'cities.txt'

obj = open(name, 'r')

ctr = 0

for l in obj:

   ctr += 1

print('Total ', ctr, ' names in this file.')

obj.close()

Explanation:

  • The file should be opened in read mode.
  • Loop through to read each line and increase the counter.
  • Display the cities in the file.