This program will compute the total mileage for all trips included in the file attached, as well as the fuel efficiency in miles per gallon. trip.txt contains: the trip number mileage gas (in gallons) Your program will open the file, read it line by line and add the miles driven and the gallons gas consumed then calculate the average fuel efficiency. It will then write Once the program has read all the lines, it will write the total miles driven, total gas consumed and the gas miles per gallon to a file called output.txt. You will assume that your txt files are located in the same directory as the code to avoid path issues. Remember that any open file will need to be closed. Example of execution: opening file trip.txt opening file output.txt output.txt will contain: total mileage: 1410 total gas consumed: 67 overall mile per gallon: 21.04
this is the trip.txt file
trip mileage gas
1 200 10
2 400 17
3 800 39
4 10 1
language: Python
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
#code
def main():
print('opening trip.txt')
#opening trip.txt file, will raise exception
if not found
file=open('trip.txt')
#reading the first line containing
labels
file.readline()
#initializing total miles and fuel to
0`
total_miles=0
total_fuel=0
#looping through each remaining lines
for line
in file:
#stripping new line
characters and splitting line by space
fields=line.strip().split(' ')
#validating
resultant array's length
if
len(fields)==3:
#reading miles and fuel, converting to int
miles=int(fields[1])
fuel=int(fields[2])
#adding to total
total_miles+=miles
total_fuel+=fuel
#closing input file
file.close()
#calculating miles per gallon
miles_per_gallon=total_miles/total_fuel
#now opening output file, writing results
and closing
print('opening
output.txt')
file=open('output.txt','w')
file.write('total mileage:
{}\n'.format(total_miles))
file.write('total gas consumed:
{}\n'.format(total_fuel))
file.write('overall miles per gallon:
{:.2f}\n'.format(miles_per_gallon))
file.close()
print('success')
#invoking main()
main()
#output
opening trip.txt
opening output.txt
success
#output.txt after running the program
total mileage: 1410 total gas consumed: 67 overall miles per gallon: 21.04
This program will compute the total mileage for all trips included in the file attached, as...