Contents
- avgData.py
- file_search.py
- file_write.py
avgData.py 1/3
[top][prev][next]
# Computes the average high temperature from a file that contains the daily
# high temperatures for last year at one location.
# By CSCI 111
DATAFILE="data/alaska.dat"
dataFile = open(DATAFILE, "r")
# initialize our line count
lineCount = 0
# initialize the total temperature
totalTemp = 0
for line in dataFile:
lineCount += 1
currentTemp = float(line)
totalTemp += currentTemp
dataFile.close()
# calculate the average
average = totalTemp/lineCount
print("The average temperature is {:6.2f}".format(average))
file_search.py 2/3
[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
# By CSCI 111
FILENAME="data/years.csv"
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 = "Senior" # later, get user input
# count the number of lines contain the searchterm
countLines = 0
# which line are we on
whichLine = 0
dataFile = open(FILENAME, "r")
# loop through all the lines in the file
for line in dataFile:
# update which line we're on
whichLine += 1
# check if the line contains the search term
if searchFor in line:
# update our countLines accumulator
countLines += 1
# display which line we found the search term on
print(whichLine)
# close the file
dataFile.close()
# display the total number of times we found the search term
print(searchFor, "is in", FILENAME, countLines, "times")
file_write.py 3/3
[top][prev][next]
# Writes content from a user to a file
# by Sara Sprenkle
PROMPT = "Enter the next line in the file: "
outfilename = input("What is the name of your output file? ")
numLines = eval(input("How many lines do you want to write? "))
# create a new file object, in "write" mode
dataFile = open(outfilename, "w")
for x in range(numLines):
userinput = input(PROMPT)
# write the user's input to the file
dataFile.write(userinput)
# write a newline after each input from the user
dataFile.write("\n")
# close the file with the method "close"
dataFile.close()
Generated by GNU Enscript 1.6.6.