Reputation: 135
Let's say I have an .odt file called "myfile.odt" in a specific directory (that's not the current working directory) and I want to replace "astring" by "anewstring", then export the modified file into a new .odt file in the current directory. How can I do that in Python?
I tried doing this with XML.Etree, but it was a bit too much for me to understand and I hit several walls, not really understanding what I did wrong. I also tried the solution provided here, but to no avail... Actually, none of the solutions from other posts managed to do it for me, ChatGPT is of no help either, and I'm struggling as I'm not used to manipulating XML-like files, which, if I understand correctly, is the appropriate way of considering and handling .odt and Word documents generally speaking.
Any tip would be great! Thanks a lot!
EDIT: apparently considering the .odt file as a text file does not work (the new file is written but is identical to the input file). Also, the odfpy library does not seem to work either due to a problem explained on their Git page. Anyone who could be able to provide an XML.Etree method (or any method that actually works) would be so kind...
EDIT 2: Here is the script I used to try to handle the file as a simple .txt file, but it resulted is the output file being corrupt and unusable, which leads me to believe that XML.Etree might be more suitable:
f1 = open('test.odt', 'r', encoding='latin')
f2 = open('newfile.odt', 'w')
for line in f1:
f2.write(line.replace('mystring', 'newstring'))
f1.close()
f2.close()
Upvotes: 1
Views: 642