Below is a pretty simple Python script to ingest some data, massage it as necessary, append a column, sort it, and then write it back to another file. Still learning all the Python best practices and APIs, so as always, any tips and tricks are appreciated! Feel free to be brutal with me if it's horrible. It's my first time trying any kind of object-orientation with the language as well, so I have no idea if I'm massacring that or not.
from collections import OrderedDict
import sys
class SkuSequence:
def __init__(self, iln, ili, sn, psn, ssd, ssc, idc):
self.inv_loc_nm = iln.strip()
self.inv_loc_id = ili
self.sku_nbr = sn
self.prt_seq_nbr = psn
self.sign_sz_desc = ssd
self.sign_sz_cd = ssc
self.inv_disp_cd = idc.strip()
self.mod_seq_nbr = "null"
def get_str_attrs(self):
attrs = []
attrs.append(str(self.inv_loc_nm))
attrs.append(str(self.inv_loc_id))
attrs.append(str(self.sku_nbr))
attrs.append(str(self.prt_seq_nbr))
attrs.append(str(self.sign_sz_desc))
attrs.append(str(self.sign_sz_cd))
attrs.append(str(self.inv_disp_cd))
attrs.append(str(self.mod_seq_nbr))
return attrs
def sort_sequence(sequence):
dict = {}
for sku in sequence:
if sku.inv_loc_id not in dict:
dict[sku.inv_loc_id] = {}
dict[sku.inv_loc_id][sku.prt_seq_nbr] = sku
for bay in dict:
dict[bay] = OrderedDict(sorted(dict[bay].items()))
return OrderedDict(sorted(dict.items()))
def convert_to_csv(header, data):
rows = []
if header is not None:
rows.append(",".join(header.get_str_attrs()))
for bay, sequence_data in data.items():
seq_nbr = 0
for sku in sequence_data.values():
if int(sku.inv_disp_cd) == 5:
sku.mod_seq_nbr = "null"
else:
seq_nbr += 1
sku.mod_seq_nbr = seq_nbr
rows.append(",".join(sku.get_str_attrs()))
return rows
def consume_data(filename):
lines = []
skus = []
with open(filename) as csv:
lines = csv.readlines()
for line in lines:
attrs = line.split(",")
skus.append(SkuSequence(attrs[0], attrs[1], attrs[2], attrs[3], attrs[4], attrs[5], attrs[6]))
return skus
def write_file(lines):
filename = sys.argv[1]
file_parts = filename.split(".")
file_parts[0] += "_resequence"
filename = ".".join(file_parts)
with open(filename, "a") as file:
for line in lines:
file.write(line + "\n")
def main():
if len(sys.argv) < 2:
print("You must provide an input filename as an argument.")
sys.exit(128)
data = consume_data(sys.argv[1])
header = data.pop(0)
header.mod_seq_nbr = "mod_seq_nbr"
sorted = sort_sequence(data)
write_file(convert_to_csv(header, sorted))
if __name__ == "__main__":
main()