"""cobol-read-sequential-file.py — write the fixed-width customer file the COBOL lesson reads, then print the control totals the COBOL program should reproduce. Layout (60 bytes per record, LF line endings, no header row): 1-6 Cust-Id 9(6) 7-31 Cust-Name X(25) 32-46 Cust-City X(15) 47-55 Cust-Balance 9(7)V99 (nine digits, implied two decimals, no sign) 56 Cust-DC X D = customer owes us, C = customer in credit 57-60 filler X(4) Run from the site folder: python code/cobol-read-sequential-file.py Writes datasets/cobol-read-sequential-file.dat and prints the totals. Standard library only (Python 3.8+). """ import os from decimal import Decimal CUSTOMERS = [ (100001, "MARGARET OKONKWO", "GALWAY", "1250.75", "D"), (100002, "TOMAS LINDQVIST", "MALMO", "0.00", "D"), (100003, "AISHA RAHMAN", "LEEDS", "318.40", "C"), (100004, "DIEGO FERNANDEZ SOTO", "SEVILLA", "9875.00", "D"), (100005, "HANNAH BRENNAN", "CORK", "42.19", "D"), (100006, "KWAME MENSAH", "ACCRA", "1500.00", "C"), (100007, "YUKI TANAKA", "OSAKA", "77.77", "D"), (100008, "LUCAS MOREIRA", "PORTO", "2200.10", "D"), (100009, "ELENA PETROVA", "VARNA", "5.05", "C"), (100010, "SAMUEL ADEYEMI", "LAGOS", "12000.00", "D"), (100011, "NORA HAUGEN", "BERGEN", "640.00", "C"), (100012, "PRIYA NAIR", "KOCHI", "3199.99", "D"), ] def record(cust_id, name, city, balance, flag): cents = int(Decimal(balance) * 100) line = f"{cust_id:06d}{name:<25}{city:<15}{cents:09d}{flag}{'':4}" assert len(line) == 60, (len(line), line) return line def main(): here = os.path.dirname(os.path.abspath(__file__)) out = os.path.join(here, os.pardir, "datasets", "cobol-read-sequential-file.dat") with open(out, "w", encoding="ascii", newline="\n") as f: for row in CUSTOMERS: f.write(record(*row) + "\n") debit = sum(Decimal(b) for _, _, _, b, fl in CUSTOMERS if fl == "D") credit = sum(Decimal(b) for _, _, _, b, fl in CUSTOMERS if fl == "C") print(f"wrote {len(CUSTOMERS)} records to {os.path.normpath(out)}") print(f"Records read : {len(CUSTOMERS)}") print(f"Debit total : {debit}") print(f"Credit total : {credit}") print(f"Net owed : {debit - credit}") if __name__ == "__main__": main()