python123
an anonymous user
·
Python
import csv
from datetime import datetime
import os
def retrieve_order_history(customer_id, file_path='order_history.csv'):
try:
with open(file_path, 'r') as file:
reader = csv.reader(file)
order_history = [row for row in reader if row[3].isdigit() and int(row[3]) == int(customer_id)]
return order_history
except FileNotFoundError:
raise # Raising the exception to be handled in the main menu
except Exception as e:
print(f"An error occurred: {e}")
return []
def add_new_order(order_id, order_date, order_amount, customer_id, file_path='order_history.csv'):
try:
mode = 'a' if os.path.exists(file_path) else 'w'
with open(file_path, mode, newline='') as file:
writer = csv.writer(file)
if mode == 'w':
# Write header if the file is newly created
writer.writerow(['orderid', 'orderdate', 'orderamount', 'customerid'])
# Check if the customer ID can be converted to an integer before writing
if customer_id.isdigit():
writer.writerow([order_id, order_date, order_amount, customer_id])
print("Order added successfully.")
else:
print("Invalid customer ID. Order not added.")
except Exception as e:
print(f"An error occurred: {e}")
def main():
while True:
print("\nMenu:")
print("1. Retrieve Order History")
print("2. Add New Order")
print("3. Exit")
choice = input("Enter your choice (1/2/3): ")
if choice == '1':
customer_id_to_search = input("Enter Customer ID: ")
try:
order_history_result = retrieve_order_history(customer_id_to_search)
print(f"\nOrder History for Customer {customer_id_to_search}:")
for order in order_history_result:
print(order)
except FileNotFoundError:
print(f"File not found: order_history.csv")
except Exception as e:
print(f"An error occurred: {e}")
elif choice == '2':
num_orders = int(input("Enter the number of orders you want to add: "))
for _ in range(num_orders):
new_order_id = input("Enter Order ID: ")
new_order_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
new_order_amount = float(input("Enter Order Amount: "))
new_customer_id = input("Enter Customer ID: ")
add_new_order(new_order_id, new_order_date, new_order_amount, new_customer_id)
elif choice == '3':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter 1, 2, or 3.")
if __name__ == "__main__":
main()
Output
Embed on website
To embed this program on your website, copy the following code and paste it into your website's HTML:
Comments
This comment belongs to a banned user and is only visible to admins.
This comment belongs to a deleted user and is only visible to admins.