The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Build a script to track fuel efficiency

Here’s a simple Python script that allows a user to track fuel efficiency (e.g., miles per gallon or kilometers per liter) over multiple entries. The script stores data locally in a CSV file so it persists across sessions.

python
import csv import os DATA_FILE = 'fuel_efficiency_log.csv' def initialize_file(): if not os.path.exists(DATA_FILE): with open(DATA_FILE, mode='w', newline='') as file: writer = csv.writer(file) writer.writerow(['Date', 'Distance (km)', 'Fuel Used (liters)', 'Efficiency (km/l)']) def log_trip(date, distance_km, fuel_liters): efficiency = round(distance_km / fuel_liters, 2) with open(DATA_FILE, mode='a', newline='') as file: writer = csv.writer(file) writer.writerow([date, distance_km, fuel_liters, efficiency]) print(f"Trip logged: {efficiency} km/l") def show_logs(): if not os.path.exists(DATA_FILE): print("No data found.") return with open(DATA_FILE, mode='r') as file: reader = csv.reader(file) for row in reader: print('t'.join(row)) def main(): initialize_file() while True: print("nFuel Efficiency Tracker") print("1. Log new trip") print("2. Show log") print("3. Exit") choice = input("Choose an option: ") if choice == '1': date = input("Enter date (YYYY-MM-DD): ") distance = float(input("Enter distance traveled (km): ")) fuel = float(input("Enter fuel used (liters): ")) log_trip(date, distance, fuel) elif choice == '2': show_logs() elif choice == '3': print("Goodbye!") break else: print("Invalid choice. Please try again.") if __name__ == "__main__": main()

Features:

  • Records date, distance, fuel used, and calculated efficiency.

  • Stores data in a CSV file for future reference.

  • CLI-based interaction, suitable for terminal/console use.

Notes:

  • You can switch to miles/gallons by modifying the unit names and efficiency formula (miles / gallons).

  • For web or mobile version, let me know if you want to upgrade this into a Flask app or React interface.

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About