0

I have a folder called InputFiles where I have multiple .doc type files with an image in each file. I want python to go to each document search, find and replace an image and then save the document in the OutputFiles. The code currently opens and saves the document if is an .rft but will not save the image, just the document. How do I get it to work with .doc and do what I need it to do.

The image file is saved in a folder called Pictures and the picture is called HR_simo.png

import os
from docx import Document
document = Document()
sourcepath = os.listdir ('InputFiles/')
for file in sourcepath:
    inputfile = 'InputFiles/' +file
    with open (inputfile, 'r') as inputfile:
        filedata = inputfile.read()
        document.add_picture('Pictures/HR_Simo.png', width=Inches(1.25))
        destinationpath ='OutputFiles/' +file
    with open(destinationpath, 'w') as file:
        file.write(filedata)
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
Simona Buga
  • 341
  • 6
  • 22
  • 1
    Pasting source code is easy (and important to do right, especially in Python where indentation matters): Just copy/paste it into the editor, highlight it and press Ctrl-K. – Tim Pietzcker Jun 18 '18 at 09:59
  • 1
    About your question: What is this `docx` module? Are you sure you need it to modify a `.doc` file, not a `.docx` file? Also, your code doesn't modify `filedata` at all, so it's no wonder it doesn't contain the image. – Tim Pietzcker Jun 18 '18 at 10:04
  • Thank you so much for responding I'm really new to programming. I'm using an extension from http://python-docx.readthedocs.io/en/latest/user/documents.html that I'm importing to generate this import. I would love to save as a .docx, but I don't think is supported. How do I modify the filedata to import an image? – Simona Buga Jun 18 '18 at 10:20
  • working with .doc is slightly harer than .docx, which is newer format. consider dumping to html with headless libreoffice and picking file from the associated folder. consider link like https://stackoverflow.com/questions/22062973/libreoffice-convert-to-not-working foir reference – Evgeny Jun 18 '18 at 10:35

0 Answers0