Contents
- avgData.py
- file_search.py
avgData.py 1/2
[top][prev][next]
# Computes the average high temperature from a file that contains the daily
# high temperatures for last year at one location.
# CSCI 111
DATAFILE="data/alaska.dat"
# open the file
dataFile = open(DATAFILE, "r")
# initialize the sum accumulator
sumOfTemperatures = 0
# initialize the number of lines in the file accumulator
numOfTemperatures = 0
# read each line of the file
for line in dataFile:
# convert the line to a float to represent the temperature
temperature = float(line)
# add the temperature to the sum
sumOfTemperatures += temperature
# update the number of temperatures
numOfTemperatures += 1
# close the file
dataFile.close()
# divide the sum by the number of temperatures in the file.
avgTemperature = sumOfTemperatures/numOfTemperatures
# display the results (twice) to show two different ways to use format.
print("The average temperature is {:.2f}".format(avgTemperature))
print("The average temperature is", "{:.2f}".format(avgTemperature))
file_search.py 2/2
[top][prev][next]
# Given a file and a term to search for,
# find which lines the term is on and the
# total number of lines that contained that term
# CSCI 111
FILENAME="data/years.dat"
print("This program will find out how many lines the given search term")
print("is on in", FILENAME,"and show those lines")
print()
print("Looking at file", FILENAME)
searchFor = "20"
#searchFor = input("What term do you want to search for? ")
lineNumber = 0
numOccurrences = 0
whichLines = []
openfile = open(FILENAME, "r")
for line in openfile:
lineNumber += 1
if searchFor in line:
numOccurrences += 1
line = line.strip()
whichLines.append(line)
print( lineNumber, line )
openfile.close()
print(searchFor, "occurs", numOccurrences, "times in")
#print(whichLines)
for line in whichLines:
print(line)
Generated by GNU Enscript 1.6.6.