python lxml tree, line[] creating multiple lines, desire single line output

前端 未结 1 748
渐次进展
渐次进展 2021-01-28 07:36

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

相关标签:
1条回答
  • 2021-01-28 08:24

    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'
    
    0 讨论(0)
提交回复
热议问题