Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This script helps you to calculate the total income from a Google merchants payment report CSV file.
#!/usr/bin/env python
import csv
import sys
import os.path
from decimal import Decimal
def endswith_case_insensitive(a, b):
a_lower = a.lower()
b_lower = b.lower()
return a_lower.endswith(b_lower)
print("This script helps you to calculate the total income from a Google merchants payment report CSV file.")
# use "earnings.csv" as default
filename = "earnings.csv"
filename_input = input("Filename of the CSV file (\"earnings.csv\"): ")
if filename_input:
filename = filename_input
# add file extension if not exists
if not endswith_case_insensitive(filename, ".csv"):
filename += ".csv"
# abort if file not exists
if not os.path.isfile(filename):
print("The file \"" + filename + "\" doesn't exist.")
sys.exit(2)
product_id = input("App package (optional): ")
sku_id = input("SKU ID (optional): ")
print("Reading file \"" + filename + "\"...")
with open(filename, encoding="utf8") as csv_file:
reader = csv.DictReader(csv_file)
i = 0
currency = ""
income_sum = Decimal(0)
for row in reader:
i += 1
if not currency:
currency = row["Merchant Currency"]
elif currency != row["Merchant Currency"]:
print("The file contains multiple merchant currencies and therefore can't be parsed.")
sys.exit(3)
if (not product_id or product_id == row["Product id"]) and (not sku_id or sku_id == row["Sku Id"]):
income_sum += Decimal(row["Amount (Merchant Currency)"])
print("Parsed " + str(i) + " elements.")
if not currency:
print("Income sum: " + str(income_sum) + " (no currency)")
else:
print("Sum: " + str(income_sum) + " " + str(currency))
@heinrichreimer

This comment has been minimized.

Copy link
Owner Author

@heinrichreimer heinrichreimer commented Mar 30, 2017

Needs Python 3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment