[Python] Python editing file in loop, how to keep changes after each (xml)

Discussão em 'Python' iniciado por Stack, Abril 18, 2025.

  1. Stack

    Stack Membro Participativo

    I need to clean few xml files from not needed elements, came up with this wild card replacement for nothing to get rid of not needed <EmbeddedImage>, but I'm missing how to store each change in the loop, looks like it overwrites it each time. Thought that Python will keep it, but it's not the case. Do I need to create some additional logic to get only single Brand_1 in my final tree?

    Appreciate if you point me how I can fix it.

    import re
    from bs4 import BeautifulSoup as bs
    filepath = "C://ddd/test.xml"

    xml = '''
    <Images>
    <EmbeddedImage Name="Brand_1">
    <ImageData>/9j/4AAQSkZJB//2Q==</ImageData>
    </EmbeddedImage>
    <EmbeddedImage Name="Brand__2XX">
    <ImageData>/9j/4AAQSkZJB//2Q==JB//2</ImageData>
    </EmbeddedImage>
    <EmbeddedImage Name="Brand___3XX">
    <ImageData>/9j/4AAQSkZAAQSkkB//2Q=AAQSk=</ImageData>
    </EmbeddedImage>
    <Images>'''

    Bs_data = bs(xml,'xml') #contant = xml ??
    content = xml
    for item in Bs_data.select ('EmbeddedImage'):
    #print('Name= ',item.get('Name'))
    if item.get('Name') != 'Brand_1':
    wild = '<EmbeddedImage Name="'+item.get('Name')+'">.*</EmbeddedImage>' ##<@><< first </ How???
    content = re.sub(wild, '', content , flags=re.DOTALL)
    print ('------------',wild,'::::',content)

    print(content) # only Brand_1

    Continue reading...

Compartilhe esta Página