can't open word document after string replacements

Frederic Rentsch anthra.norell at vtxmail.ch
Tue Oct 24 18:28:48 CEST 2006


Antoine De Groote wrote:
> Hi there,
>
> 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?
>
> Oh, and is this approach pythonic anyway? (I have a strong Java background.)
>
> Regards,
> antoine
>
>
> import os
>
> members = somelist
>
> os.chdir(somefolder)
>
> doc = file('ttt.doc', 'rb')
> docout = file('ttt1.doc', 'wb')
>
> counter = 0
>
> for line in doc:
>      while line.find('ABCDEF') > -1:
>          try:
>              line = line.replace('ABCDEF', members[counter], 1)
>              docout.write(line)
>              counter += 1
>          except:
>              docout.write(line.replace('ABCDEF', '', 1))
>      else:
>          docout.write(line)
>
> doc.close()
> docout.close()
>
>   
DOC files contain housekeeping info which becomes inconsistent if you 
change text. Possibly you can exchange stuff of equal length but that 
wouldn't serve your purpose. RTF files let you do substitutions and they 
save a lot of space too. But I kind of doubt whether RTF files can 
contain pictures.

Frederic






More information about the Python-list mailing list