Search code examples
pythoninstallationpython-docx

Installing python-docx on pycharm 2017


I am having real trouble with this. Wasted a bunch of hours and just can't get it figured out. I would appreciate any help.

I have installed python-docx on Pycharm. I run the following code:

from docx import Document
from docx.shared import Inches

And i receive the following error message:

ImportError: cannot import name 'Document'

I have seen a number of different explanations ... need to update lxml, need to update PIL need to check source folder ... and I have not been able to make anything work and it is becoming very frustrating.

I am on a MAC OS X 10.10.5


Solution

  • Pretty good chance you have 'docx' installed rather than 'python-docx'. 'docx' was the package name for the legacy version, v0.2 and before. It has a completely different API and doesn't have a Document class. Consequently it gives this exact error. If python-docx just wasn't installed it would be more like no package named docx.

    You can confirm this with pip freeze:

    $ pip freeze
    ...
    docx=0.2.0
    ...
    python-docx=0.8.6
    ...
    

    You can only have one installed; they can't co-exist because the root module name is docx in both cases. Which one gets imported as docx depends on installation order and perhaps other factors; short story is you should get rid of the old one.

    Depending on what pip freeze shows you, you'll want to uninstall docx and install or reinstall python-docx. Safest would be to uninstall them both and then reinstall python-docx.

    $ pip uninstall docx
    $ pip uninstall python-docx
    $ pip install python-docx