I\'m am creating an xml file with python using lxml. I am parsing through a file by line, looking for a string, and if that string exists, I create a SubElement. I am assignin
Your lines include the line separator, \n
. You can strip the line with str.rstrip():
with open(file) as openfile:
for line in openfile:
if "[testclass]" in line:
etree.SubElement(subroot, "tagxyz").text = line.rstrip('\n')
In future, use the repr() function to debug such issues; you'll readily see the newline represented by its Python escape sequence:
>>> line = '[testclass] unique_value_horse\n'
>>> print(line)
[testclass] unique_value_horse
>>> print(repr(line))
'[testclass] unique_value_horse\n'
>>> print(repr(line.rstrip('\n')))
'[testclass] unique_value_horse'