186k views
3 votes
Create a Python program that

Opens a file and reads the contents of the following file
trips.txt
The file contains several lines of data, with each data item separated by commas. The data is:
A trip date
The amount of fuel used on the trip
The number of miles traveled on the trip
For each of the lines of data in the file, separate the data items and put them in appropriate variables
The file contents are in the form of strings, so you must convert the numbers in the data into the proper type
Calculate the fuel mileage achieved on each trip
Display on a single line the:
Trip data
Amount of fuel used
Numbers of miles traveled
Fuel mileage calculated for the trip
Create a new file to save the data read and the fuel mileage calculated for the trip
Write the data on separate lines for each trip in the data, with each item separated by commas
Remember that all of the data must be saved in the string form

1 Answer

6 votes

Answer: Provided in the explanation section

Step-by-step explanation:

Code to run this can be seen below:

# create list to store data from file

dates = [] # date of trip

fuel_used = [] # amount of fuel used on trip

miles_traveled = [] # number of miles traveled on trip

mileage = [] # mileage calculated

# open the input text file

file = open("trips.txt", "r") # open file in read only mode

# file contains each trip data on separate lines

# each data value is separated by comma

# read all data into arrays

while True:

line = file.readline() # read file line by line

# check for end of file

if line == "":

break

data = line.split(",") # separate each data from line

# fill list with data

dates.append(data[0])

fuel_used.append(int(data[1]))

miles_traveled.append(int(data[2]))

fuel = int(data[1])

miles = int(data[2])

mileage_calculated = miles / fuel

# add mileage into list

mileage.append(mileage_calculated)

# close the file

file.close()

# display data

print("{:15s}{:10s}{:10s}{:10s}".format("Date", "Fuel", "Miles", "Mileage"))

for i in range(len(dates)):

print(dates[i].ljust(15) + str(fuel_used[i]).ljust(10), end="")

print(str(miles_traveled[i]).ljust(10) + "{:.2f}".ljust(10).format(mileage[i]))

# open file to write data

file = open("fuel_mileage.txt", "w") # create a new file or overwrite existing one

# write data to file

for i in range(len(dates)):

trip_data = dates[i] + "," + str(fuel_used[i]) + "," + str(miles_traveled[i]) + "," + "{:.2f}\\".format(mileage[i])

file.write(trip_data)

# close the file

file.close()

cheers i hope this helped !!!

User Seddy
by
3.2k points