Akhaylin 0 Newbie Poster

I am tasked with this excercise:
Edit the Python file processData (or use it as a guide when you create a new Python file) so it
reads in the data from population.txt, checks to make sure the file exists and is in the right
format (if it isn’t throw an appropriate exception), calculates the combined population of the
countries in the text file and prints that total.

however am stuck as my code will mot print total and will only change .txt file please help

This program processes a file containing a count followed by data values.
If the file doesn't exist or the format is incorrect, you can specify another file.

#

def main() :
   done = False
   while not done :
      try :
     filename = input("Please enter the file name: ")
     data = readFile(filename)

     # As an example for processing the data, we compute the sum.
     total = 0
     for value in data[:5]:
        total = total + value

     o=open("output.txt","w")
     o.write("The sum is "+ str(total))
     done = True

  except IOError :
     print("Error: file not found.")

  except ValueError : 
     print("Error: file contents invalid.")

  except RuntimeError as error :
     print("Error:", str(error))
Opens a file and reads a data set.
@param filename the name of the file holding the data
@return a list containing the data in the file

#

def readFile(filename) :
   inFile = open(filename, "r")   
   try :
  return readData(inFile)
   finally :
      inFile.close()
Reads a data set.
@param inFile the input file containing the data
@return the data set in a list

#

def readData(inFile) :
   data = []
   for line in inFile:
      line =line.split(":")
      value = int(line[1])        # May raise a ValueError exception.
      data.append(value)
Make sure there are no more values in the file.
  line = inFile.readline()
   if line != "" :          
  raise RuntimeError("End of file expected.")
   return data
Start the program.
   main()

Dani AI

Generated

In 's post two things explain the observed behaviour: the loop for value in data[:5] only sums the first five entries, and the result is sent to output.txt instead of being printed, so nothing appears on the console. The file-parsing step is also fragile: splitting with line.split(":") and indexing line[1] will fail if a line lacks a colon or contains commas/extra whitespace.

A compact, robust approach that validates the leading count, parses lines as Country:population, strips commas/whitespace, and prints the total:

def process_population_file(filename):
    with open(filename, 'r') as f:
        count_line = f.readline()
        count = int(count_line.strip())                      # raises ValueError if bad
        values = []
        for i in range(count):
            line = f.readline()
            if not line:
                raise RuntimeError("File ended before {} records.".format(count))
            parts = line.strip().split(':', 1)
            if len(parts) != 2:
                raise ValueError("Record {} not 'Name:population'.".format(i+1))
            pop = int(parts[1].strip().replace(',', ''))    # remove thousands separators
            values.append(pop)
        if f.read().strip():                                 # ignore harmless trailing blank lines
            raise RuntimeError("Extra data after expected records.")
    total = sum(values)
    print("The sum is", total)

Troubleshooting tips: confirm the first line is the record count and that each data line contains a colon and a numeric population (no embedded commas unless removed). Temporarily print parsed values or repr(line) to see unexpected whitespace/characters. Use with open(...) to avoid manual close and prefer sum(values) rather than slicing so all numbers are included.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.