Write a python program Write a function called solveFile(inputfilename, outputfi
ID: 3772148 • Letter: W
Question
Write a python programWrite a function called solveFile(inputfilename, outputfilename). It takes two strings parameters which are filenames. The input file will have multiple lines, where each line will be of the form a number, followed by a space, followed by one of 'add' or 'sub', followed by a space, followed by another number. The numbers will be whole numbers for e.g. a possible input file could have 23 add 7 10 add 9 3 sub 2 5 add 4 Your function should go through this file and create the output file, where each line will be the answer to the line in the input file. for the above example, the output file should have 30 19 1 9 Your function does not return anything
Explanation / Answer
Open Python 2.7 IDE, and File ->New Window and open a new window and write code
#The method definition solveFile that takes two input
#file arguments inputfilename, outputfilename .
#read input file and split the lines into words
#and check if words operation is add or sub
#then perform the mathematical operation and
#write to output file
def solveFile(inputfilename, outputfilename):
#open output file
writer=open(outputfilename,'w')
#open input file
with open(inputfilename,'r') as file:
//#read lines
lines=file.readlines()
#read each line
for line in lines:
#split line into words
words = line.split()
#conver word to int
value1=int(words[0])
#middle is operation
operation=words[1]
#conver word to int
value2=int(words[2])
#check operation is add then write to output file
if operation == "add":
writer.write(str(value1+value2)+" ")
#check operation is sub then write to output file
elif operation == "sub":
writer.write(str(value1-value2)+" ")
#close input file
file.close()
#close output file
writer.close()
#call solveFile
solveFile("input.txt", "output.txt")
-------------------------------------------------------------------------
input.txt
23 add 7
10 add 9
3 sub 2
5 add 4
output.txt
30
19
1
9
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.