[Python] How to replace a text with a respect to spaces and new lines using odfdo

Discussão em 'Python' iniciado por Stack, Janeiro 25, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following code in my Python script:

    body.replace("MAIN_TEXT", """some multiline \n\n text """)

    When I try to replace "MAIN_TEXT" with the multiline string, the result I get is: some multiline text

    How do I preserve the line breaks? This is my code:

    `
    from pathlib import Path
    from odfdo import Document

    _DOC_SEQUENCE = 700
    DATA = Path(__file__).parent / "data"
    SOURCE = "lorem.odt"
    OUTPUT_DIR = Path(__file__).parent / "recipes_output" / "replaced_text"
    TARGET = "lorem_replaced.odt"


    def save_new(document: Document, name: str):
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
    new_path = OUTPUT_DIR / name
    print("Saving:", new_path)
    document.save(new_path, pretty=True)


    def search_replace(document):
    body = document.body

    body.replace("MAIN_TEXT", """some multiline \n\n text


    """)

    def main():
    document = Document(DATA / SOURCE)
    search_replace(document)
    save_new(document, TARGET)


    if __name__ == "__main__":
    main()`

    Continue reading...

Compartilhe esta Página