- Problem 1: Write a script that reads a name from the
input file name.txt, constructs a greeting based on the name, outputs the greeting to the output file greeting.txt.
- Answer to Problem 1, pseudocode:
open input file creating file object fin
read one name from input file
close input file
construct greeting "Hello, <name>, how are you?"
open output file creating file object fout
write greeting to output file
close output fil
- Here is what you need to know for translating the pseudocode:
- Open file for reading:
fin = open("name.txt", "r")
- Read name from input file:
name = fin.readline( )
- Close the input file:
fin.close( )
- Construct greeting:
greeting = "Hello, " + name + ", how are you?"
- Open output file:
fout = open("greeting.txt", "w")
- Write greeting to output file:
fout.write(greeting)
- Close output file:
fout.close( )
- The complete script:
fin = open("name.txt", "r")
name = fin.readline( )
fin.close( )
greeting = "Hello, " + name + ", how are you?"
fout = open("greeting.txt", "w")
fout.write(greeting)
fout.close( )
- Problem 2: The file numbers.txt contains a list of floating point numbers, one number per line.
Write a script that reads these numbers one at a time, keeping track of the count and the sum of the numbers.
When finished reading write the average of the numbers to the output file average.txt.
- Answer to Problem 2, the pseudocode for computing average of a list:
initialize sum to 0.0
initialize count to 0
open input file
read next input line from input file
while not at end of list
convert input line to float value
update sum
update count
read next input line from keyboard
end
if count > 0
compute average as sum / count
write average to output file
else
print to output file "No input values."
end
close input and output files
- Here is what you need to know to translate the pseudocode:
- Open file for reading:
fin = open("numbers.txt", "r")
- Read line from input file:
line = fin.readline( )
- Add the number in the line to the sum:
sum = sum + float(line)
- Add one to the count:
count = count + 1
- Close the input file:
fin.close( )
- Open the output file:
fout = open("average.txt", "w")
- Write the average to the output file:
fout.write("Average: " + str(average))
- Close the output file:
fout.close( )
The complete script:
# Initialize summary variables.
count = 0
sum = 0.0
# Open input file.
fin = open("values.txt", "r")
# Input first value
line = fin.readline( )
# Continue to input values until the
# end of file is reached.
while line != "":
value = float(line)
# Update summary values
sum += value
count += 1
# Input next value
line = fin.readline( )
# Close input file
fin.close( )
# Open output file
fout = open("average.txt", "w")
# Compute and output average
ave = sum / count
fout.write(f"Average: {ave}\n")
# Close input file
fout.close( )