Problem 6.5

Sales by Day

Write a program sales.py to compute the total sale amount per day, given a text file with details of transactions with three columns Order Id, Date and Amount.

Here is a sample input file.

$ cat files/orders.txt
1001 2023-01-01 100
1002 2023-01-01 50
1003 2023-01-02 50
1004 2023-01-02 150
1005 2023-01-01 25

The file contains multiple transactions, one in row. Each row will have three fields, Order Id, Date and Amount, seperated by a space.

YOur program should take the order file as a command-line argument and print the total same amount per day. The output should be sorted by date.

$ python sales.py files/orders.txt
2023-01-01 175
2023-01-02 200

Solution

import sys

filename = sys.argv[1]

sales = {}
for line in open(filename):
    order_id, date, amount = line.strip().split()
    sales[date] = sales.get(date, 0) + int(amount)

for date in sorted(sales):
    print(date, sales[date])