# # file: read-from-file-mod4.py # This program asks the user to type the file name to be opened # Opens the file, and displays all the data from the file on the screen. # After that it finds the sum of numbers, and displays it on the screen. # !!! Please, note the the input file "numbers.dat" should be stored in the # same place your program is. # # The program uses readlines() function # def main(): print "This program opens a file with numbers, displays all the information on the screen, and " print "finds the sum of all the numbers." print "Please, note that the file should have one number per line, e.g.:" print "5 \n6 \n7 \n12 \n-19 \n6 \n" fname=raw_input("Please, input the name of a file you'd like to work with:") try: # if the try fails because of IOError, #then we will output the warning and stop the program in_stream=open(fname,"r") strngs=in_stream.readlines() # strngs is a list of strings, # each element refers to the corresponding line of charactes in the input file, # i.e. the 0th element refers to the first line, the 1st to the second, and so forth # let's find out how many lines/strings/numbers are there n=len(strngs) sum=0 # initially the sum is zero for i in range(n): try: # this is the place where we ignore symbols, that are not numbers # conversion of a string to an integer value next_number=int(strngs[i]) sum=sum+next_number # updating the sum except: flag=1 print "The contents of the file %s is:" % (fname) for i in range(n): if i!=n-1: print strngs[i][:-1] else: print strngs[i] print "The sum of all numbers is %d. Good buy!" % (sum) except IOError: print "Cannot open the file %s." % (fname) main()