Select Git revision
-
Chris MacLellan authoredChris MacLellan authored
LoopsAndFiles.py 3.07 KiB
#Program: LoopsAndFiles.py
#Purpose: Test different ways to process data from files
#Author: Adelaida Medlock
#Date: March 9, 2024
#count how many times a word appear in each line of a file
def countWordPerLine():
filename = input('Enter the name of the file to open: ')
word = input('Enter the word you want to count: ')
try :
inFile = open(filename)
lines = inFile.readlines()
inFile.close()
for index in range(len(lines)) :
count = lines[index].count(word)
print(word, 'appears', count, 'time(s) in line #', index)
except FileNotFoundError :
print('Could not find', filename)
# Read a bunch of floating-point values from a file,
# calculate some basic stats, and print results to screen
# and save the results in an output file as well
def computeStats():
# loop until we get a value filename
validFile = False
while not validFile :
try :
filename = input('Enter the name of the data file: ')
inFile = open(filename)
validFile = True
except FileNotFoundError :
print('Could not find', filename, 'Try again')
# read data from file and process it
lines = inFile.readlines()
inFile.close()
count = 0
total = 0.0
for item in lines :
count += 1
total = total + float(item)
average = total / count
# display results
print('\nStats for data in file')
print('Number of values:', count)
print('Sum of values: {:.2f}'.format(total))
print('Average of values: {:.2f}'.format(average))
# saving results to output file
outFile = open('stats.txt', 'w')
outFile.write('Stats for data in file\n')
outFile.write('Number of values: {:d}\n'.format(count))
outFile.write('Sum of values: {:.2f}\n'.format(total))
outFile.write('Average of values: {:.2f}\n'.format(average))
outFile.close()
# Calculate stats for values stored in a file
# Save results in a an output file
# Demo how to use the with statement so files
# are automatically closed
def withDemo(filename):
with open(filename, 'r') as inFile :
total = 0.0
count = 0
# Read one line at the time
line = inFile.readline()
while line != '' : # an empty string indicates the EOF
total = total + float(line)
count += 1
line = inFile.readline()
# Saving results to output file
outFile = open('stats2.txt', 'w')
outFile.write('Stats for data in file\n')
outFile.write('Number of values: {:d}\n'.format(count))
outFile.write('Sum of values: {:.2f}\n'.format(total))
outFile.write('Average of values: {:.2f}\n'.format(total / count))
# By using with both files are automatically closed
# Display results
print('\nStats for data in file')
print('Number of values:', count)
print('Sum of values: {:.2f}'.format(total))
print('Average of values: {:.2f}'.format(total / count))
print('Results have been saved to file stat2.txt')