From 65cdaf28d2db19fad544d81843c77a27d40bf978 Mon Sep 17 00:00:00 2001 From: David Todd Date: Tue, 26 Apr 2016 16:41:10 -0500 Subject: [PATCH] Automatically delete the temp file on startup, change the pattern The pattern or the pattern.sub is not correct and will not always match entire column This works fine for most items, but school districts are noted for cropping this error up --- README.md | 2 +- main.py | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 0490e68..799add7 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ ERP Contact Import Tool ======================= -This utility fixes the contacts csv file for importing into our ERP (Odoo) +This utility fixes the contacts csv file for importing into our ERP (Odoo) Specifically this utility will replace all the values in a csv column with a dictionary created through another csv file Copyright (c) 2016 David Todd (alopexc0de) https://c0defox.es diff --git a/main.py b/main.py index 5db85bb..7691615 100644 --- a/main.py +++ b/main.py @@ -48,6 +48,7 @@ def find_index(row=None, col=None): return index os.rename(config['import_path'], config['import_path']+'.orig') # Store the original import_path in a backup file +os.remove(config['temp_path']) # Delete the temp file if it exists for some reason with open(config['partner_path'], 'r') as partner_csv: reader = csv.reader(partner_csv) @@ -67,10 +68,10 @@ with open(config['partner_path'], 'r') as partner_csv: partner_ids = {rows[name]:rows[id] for rows in reader} # Build a dict containing the company names as the keys and the __export__IDs as values reader = None - # Open both the import_csv and temp_csv files + # Open both the import_csv (read-only) and temp_csv (write-only) files with open(config['import_path']+'.orig', 'r') as import_csv, open(config['temp_path'], 'w') as temp_csv: reader = csv.reader(import_csv) - writer = csv.writer(temp_csv, lineterminator='\n') + writer = csv.writer(temp_csv, lineterminator='\n') first_row = next(reader) if config['column_to_change'] not in first_row: @@ -83,7 +84,8 @@ with open(config['partner_path'], 'r') as partner_csv: writer.writerow(first_row) for lines in reader: # Taken from http://stackoverflow.com/a/2400577/5727514 and modified to support what I need - pattern = re.compile('|'.join(partner_ids.keys())) + pattern = re.compile(r'\b(' + '|'.join(partner_ids.keys()) + r')\b') + #pattern = re.compile('|'.join(partner_ids.keys())) lines[col] = pattern.sub(lambda x: partner_ids[x.group()], lines[col]) writer.writerow(lines)