import pandas as pd import os header = '\n
\nImport Data\n
\n\n\n\nVouchers\n\n\n\n' footer = '\n\n
\n' def CSVtoXMLpayment(inputfile): print(f"Processing file: {inputfile}") if not inputfile.lower().endswith('.csv'): print('Expected a CSV file') return 0 outputfile = os.path.splitext(inputfile)[0] + '.xml' try: df = pd.read_csv(inputfile) except FileNotFoundError: print('CSV file not found') return 0 except pd.errors.EmptyDataError: print('CSV file is empty') return 0 except pd.errors.ParserError: print('Error parsing CSV file') return 0 att = df.columns rowop = '' srop = '' for j in range(len(df)): rowop = '' v_type = '' p_name = '' invoice_num = 'emp' date = '' for i in range(len(att)): row_value = str(df[att[i]][j]) # Escape special XML characters row_value = row_value.replace('&', '&').replace('<', '<').replace('>', '>').replace("'", ''').replace('"', '"') if att[i].startswith('VOUCHERTYPENAME'): v_type = row_value rowop += f'<{att[i]}>{row_value}\n' continue if att[i].startswith('DebitLedger'): p_name = row_value if row_value == 'emp': continue if v_type == 'Receipt': bank_name = row_value rowop += f'\n{row_value}\n' continue if att[i].startswith('AmountDebit'): if v_type == 'Payment' and invoice_num == 'emp': rowop += f'Yes\nYes\n{row_value}\n\n' elif v_type == 'Payment' and invoice_num != 'emp': rowop += f'Yes\nYes\n{row_value}\n\n{invoice_num}\nNew Ref\n{row_value}\n\n\n' elif v_type == 'Contra': rowop += f'Yes\nYes\n{row_value}\n\n' else: rowop += f'Yes\nYes\n{row_value}\n\n{date}\n{date}\n{p_name}\nCheque/DD\n{df[att[i+1]][j]}\nTransacted\n{df[att[i+1]][j]}\n{row_value}\n\n\n' continue if att[i].startswith('CreditLedger'): if v_type == 'Payment': bank_name = row_value rowop += f'\n{row_value}\n' continue if att[i].startswith('AmountCredit'): if row_value == 'emp' and i == len(att) - 1: rowop += f'\n\n' continue if v_type == 'Receipt' and invoice_num == 'emp': rowop += f'No\nYes\n{row_value}\n\n\n\n' elif v_type == 'Receipt' and invoice_num != 'emp': rowop += f'No\nYes\n{row_value}\n\n{invoice_num}\nNew Ref\n{row_value}\n\n\n\n\n' elif v_type == 'Contra': rowop += f'No\nYes\n{row_value}\n\n\n\n' else: rowop += f'No\nYes\n{row_value}\n\n{date}\n{date}\n{p_name}\nCheque/DD\n{p_name}\nTransacted\n{p_name}\n{row_value}\n\n\n\n\n' continue if att[i].startswith('Invoice'): invoice_num = row_value if v_type != 'Contra' and invoice_num != 'emp': rowop += f'{row_value}\n' continue if att[i].startswith('DATE'): date = row_value rowop += f'<{att[i]}>{row_value}\n' continue # Default case for other fields rowop += f'<{att[i]}>{row_value}\n' srop += f'\n\n{p_name}\n' + rowop entireop = header + srop + footer try: with open(outputfile, 'w+') as f: f.write(entireop) print(f"XML file created successfully: {outputfile}") except Exception as e: print(f"Failed to write XML file: {e}") return 0 return outputfile # Call the function with the correct file path CSVtoXMLpayment('/var/folders/m0/1znp8qrn26584wd5qf8g1gvm0000gp/T/tmp4wg037ba.csv')