1. Lab05a.py
– Writing to a text file
#
# Name:
# File: Lab05a.py
# Date: February 7, 2008
#
# Desc: Generate and
write a compund interest table
# to a text file
def main():
#
Display title
print
print "Writing to a Textfile"
print
# Get
Filename and open it for output
filename = raw_input("Enter file name: ")
outfile = open(filename, 'w')
# Get
Present Value, Annual Interest Rate, and Number of Years
print
PV
= input("Enter present value: ")
apr = input("Enter annual
interest rate as a percent: ");
apr = apr /100.0 # convert to
decimal
nYears = input("Enter the
number of years: ")
#
Write Column Headers to text file
outfile.write('\n')
outfile.write(" |
Present | Interest | Future
|\n")
outfile.write("
Year | Value | Earned |
Value |\n")
outfile.write("------+----------+----------+----------+\n")
# Generate
Table
for
i in range(nYears):
interest = PV * apr # compute interest
FV = PV + interest # compute future value
outfile.write(" %2d | %8.2f | %8.2f | %8.2f |\n"
% (i+1, PV, interest,
FV))
PV = FV # update
present value
# close file and announce end of program
outfile.close()
print
print "End of Pgm"
print
main()
2. Lab05b.py – Number
crunching numerical data read from a text file
#
# Name:
# File: Lab05b.py
# Date: February 7, 2008
#
# Desc: Reads a text
file of numerical data and computes
# the mean, variance and standard
deviation
import math
def main():
#
Display Title
print
print "Number Crunching a Data File for Mean and Standard
Deviation"
print
#
Get file name for data and open
for input
filename = raw_input("Enter the name of the input file: ")
infile = open(filename, 'r')
# Compute
mean
sum
= 0.0
count = 0;
for
num in infile:
sum = sum + float(num)
count = count + 1
mean = sum / count
# Close and re-open
file so we can use same data
# to compute the variance and
standard deviation
infile.close()
infile = open(filename, 'r')
# Compute
variance and standard deviation
sum
= 0.0
for
num in infile:
sum = sum + (float(num) -
mean)*(float(num)-mean)
variance = sum / count
sd = math.sqrt(variance)
#
Display results (uses string
formatting)
print
print "Mean =
%8.4f" % (mean)
print "Variance = %8.4f"
% (variance)
print "Standard Deviation = %8.4f" % (sd)
print
#
close file for last time
infile.close()
main()