can't open word document after string replacements

Daniel Dittmar daniel.dittmar at sap.com
Tue Oct 24 04:35:01 EDT 2006


Antoine De Groote wrote:
> I have a word document containing pictures and text. This documents 
> holds several 'ABCDEF' strings which serve as a placeholder for names. 
> Now I want to replace these occurences with names in a list (members). I 
> open both input and output file in binary mode and do the 
> transformation. However, I can't open the resulting file, Word just 
> telling that there was an error. Does anybody what I am doing wrong?

The Word document format probably contains some length information about 
paragraphs etc. If you change a string to another one of a different 
length, this length information will no longer match the data and the 
document structure will be hosed.

Possible solutions:
1. Use OLE automation (in the python win32 package) to open the file in 
Word and use Word search and replace. Your script could then directly 
print the document, which you probably have to do anyway.

2. Export the template document to RTF. This is a text format and can be 
more easily manipulated with Python.

> for line in doc:

I don't think that what you get here is actually a line of you document. 
Due to the binary nature of the format, it is an arbitrary chunk.

Daniel



More information about the Python-list mailing list