0

I'm trying to convert a file from csv to xml by doing some replaces. I don't know if this is the best way but sounded a simpler and easy way to do it, since the files are quite simple. The thing is, the last replace I have to do is a regex and I don't know how to append that to all the replaces that come before.

import re
text = open("input.csv", "r")
x = open("output.xml","w")
for line in text:
    x.write(line.replace("QWERT=", "<Doc3045 QWERT=\"") \
    .replace(",Date=", "\" Date=\"") \
    .replace("ABCDE,Tp,CD", "") \
    .replace("S,1,", "<Cli Tp=\"1\" ABCDE=\"S\" Cd=\"") \
    .replace(",", "\">"))
#regex replace should go here
text.close()
x.close()

I already have the regex replace ready:

line = re.sub(r'(\d$)', r'\1"/>', line)

but I couldn't find a way to apply it inside the for within the input file or even to open the output file and applying the regex.

Adami
  • 335
  • 5
  • 15
  • 1
    Why don't you just make apply the replaces for `line` to line itself, then apply the sub function to it, and THEN use `x.write(line)`? – Robo Mop Sep 18 '20 at 20:47
  • Not sure if a duplicate (because your question is actually about combining replace and sub) but this should help: https://stackoverflow.com/questions/41059264/simple-csv-to-xml-conversion-python – Tomerikoo Sep 18 '20 at 20:50

0 Answers0