Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import csv
- def readData():
- fields = ("name", "city", "miles", "gallons")
- f = open("travel.txt", "r")
- travels = [] # create empty list
- dReader = csv.DictReader(f, fieldnames=fields, delimiter="\t") # read file f, using fields by tab
- for row in dReader: # each row is converted to a dictionary
- travels.append(row) # append dictionary to list
- f.close()
- return travels # return list of dictionaries
- def displayData(trips): # trips is the list of dictionaries
- fs = "%-8s %-16s %7s %s" # create format string
- print(fs % ("Name", "City", "Miles", "Gallons")) # print header
- print()
- for t in trips: # t is a dictionary
- fs = "%-8s %-16s %6s %5s" # makes format string
- print(fs % (t['name'].title(), t['city'].title(), t['miles'], t['gallons']))
- def calculateData(trips):
- totalM = []
- totalG = []
- print()
- userName = input("Enter user's first name: ").lower()
- print()
- for row in trips:
- if row.get('name') == userName:
- totalM.append(float(row.get('miles')))
- totalG.append(float(row.get('gallons')))
- totalMiles = sum(totalM)
- totalGallons = sum(totalG)
- mpg = totalMiles / totalGallons
- cost = totalMiles * 0.75
- print('Name: ', userName.title())
- print("Total miles: ", "%.2f" % totalMiles)
- print("Total gallons: ", "%.2f" % totalGallons)
- print("mpg = ", "%.2f" % mpg)
- print("Owed: $", "%.2f" % cost, "at 75 cents per mile")
- def addTrip(trips):
- nom = input("Enter your first name: ")
- city = input("Enter destination city: ")
- mi = input("Enter miles traveled: ") # get user input, create dictionary, add to list
- gal = input( "Enter gallons used: ") # all the data are strings
- record = {'name' : nom, 'city' : city, 'miles' : mi, 'gallons' : gal} # create the dictionary
- trips.append(record) # append dictionary to list
- return trips
- def storeData(trips):
- fields = ("name", "city", "miles", "gallons")
- f = open("travel.txt", "w")
- dWriter = csv.DictWriter(f, fieldnames=fields, delimiter="\t", lineterminator="\n") # get file ready
- dWriter.writerows(trips) # write the whole list of dictionaries to tab separated text file
- f.close()
- def main():
- travel_log = readData() # read file, convert records to a list of dictionaries
- while True:
- print("""
- Menu options. Choose 1, 2, 3, or 4
- 1. Display all trip data
- 2. Calculate user data
- 3. Add a trip
- 4. Save and exit
- """)
- opt = input(" Enter your choice, 1, 2, 3 or 4: ")
- if opt == "1":
- print() #prints a blank line
- displayData(travel_log)
- elif opt == "2":
- calculateData(travel_log)
- elif opt == "3":
- travel_log = addTrip(travel_log)
- elif opt == "4":
- storeData(travel_log)
- print("Goodbye")
- print()
- break #exit loop
- else:
- print("Invalid entry, please re-enter your choice")
- print()
- main() # Call main(), execute the program
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement