Skip to content

Instantly share code, notes, and snippets.

@seanlaw
Last active May 6, 2020 01:55
Show Gist options
  • Save seanlaw/76799c699cd96d655e704d16fa3bc58f to your computer and use it in GitHub Desktop.
Save seanlaw/76799c699cd96d655e704d16fa3bc58f to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import argparse
def parse_orders(fname, outname=None, encoding="Windows-1252"):
if outname is not None:
fout = open(outname, "w")
with open(fname, encoding=encoding) as f:
date = None
check = None
quantity = None
item = None
price = None
for line in f:
line = line.strip()
tokens = line.split()
# Date
if len(tokens) >= 2 and tokens[0].startswith("Date"):
date = tokens[1]
# Check
if len(tokens) >= 2 and tokens[0].startswith("Check"):
check = tokens[2]
if date is not None and check is not None:
# Quantity, Item
if len(tokens) >= 3 and tokens[1] == "X":
quantity = tokens[0]
if tokens[-1].startswith("$"):
item = " ".join(tokens[2:-1])
price = tokens[-1][1:]
else:
item = " ".join(tokens[2:])
if len(tokens) >= 1 and tokens[0].startswith("$"):
# Price
price = tokens[0][1:]
# Print output and reset
if quantity is not None and item is not None and price is not None:
out = f'"{date}","{check}","{quantity}","{item}","{price}"'
if outname is not None:
fout.write(out + "\n")
else:
print(out)
quantity = None
item = None
price = None
# Subtotal
if len(tokens) >= 1 and tokens[0].startswith("Subtotal"):
check = None
date = None
if outname is not None:
fout.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-out", help="Specify an output file name", default=None)
parser.add_argument("inp", help="Specify an input file to parse")
args = parser.parse_args()
parse_orders(args.inp, args.out)
@seanlaw
Copy link
Author

seanlaw commented May 6, 2020

From the command line, you can do:

python orders_to_csv.py -out output.csv input.txt

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