Import docx python ошибка

when I import docx I have this error:

  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/docx-0.2.4-py3.3.egg/docx.py", line 30, in <module>
    from exceptions import PendingDeprecationWarning
ImportError: No module named 'exceptions'

How to fix this error (python3.3, docx 0.2.4)?

wjandrea's user avatar

wjandrea

27.3k9 gold badges59 silver badges80 bronze badges

asked Mar 31, 2014 at 15:11

user3472559's user avatar

1

If you are using python 3x don’t do pip install docx instead go for

pip install python-docx 

It is compatible with python 3.x

Official Documentation available here: https://pypi.org/project/python-docx/

Jean-Francois T.'s user avatar

answered May 29, 2017 at 2:21

Arun's user avatar

ArunArun

3,3901 gold badge11 silver badges19 bronze badges

3

When want to use import docx, be sure to install python-docx, not docx.You can install the module by running pip install python-docx.

The installation name docx is for a different module
However,

when you are going to import the python-docx module,
you’ll need to run
import docx, not import python-docx.

if still you want to use docx module then:

First of all, you will need to make sure that the docx module is installed.
If not then simply run pip install docx.
If it shows ‘*requirement already satisfied*’
then the solution is :

  1. Go to the library to find docx.py file,
    you’ll need to go to directory where you installed python then Libsite-packages and find docx.py file
  2. Open docx.py file in text editor and find this code

    from exceptions import PendingDeprecationWarning
    
  3. Replace the above code with
try:
    from exceptions import PendingDeprecationWarning
except ImportError:
    pass
  1. Save the file
  2. Now you can run import docx module in Python 3.x without any problem

answered Jun 13, 2020 at 16:43

Sameer Khan's user avatar

Sameer KhanSameer Khan

3213 silver badges4 bronze badges

  1. Uninstall docx module with pip uninstall docx
  2. Download python_docx-0.8.6-py2.py3-none-any.whl file from http://www.lfd.uci.edu/~gohlke/pythonlibs/
  3. Run pip install python_docx-0.8.6-py2.py3-none-any.whl to reinstall docx.

This solved the above import error smoothly for me.

wjandrea's user avatar

wjandrea

27.3k9 gold badges59 silver badges80 bronze badges

answered Mar 4, 2017 at 2:56

Vancent's user avatar

VancentVancent

4775 silver badges16 bronze badges

0

If you’re using python 3.x, Make sure you have both python-docx & docx installed.

Installing python-docx :

pip install python-docx

Installing docx :

pip install docx

answered Apr 26, 2020 at 14:20

Kalpit's user avatar

KalpitKalpit

1711 silver badge5 bronze badges

In Python 3 exceptions module was removed and all standard exceptions were moved to builtin module. Thus meaning that there is no more need to do explicit import of any standard exceptions.

copied from

answered Apr 10, 2018 at 14:39

sajid's user avatar

sajidsajid

7788 silver badges23 bronze badges

pip install python-docx

this worked for me, try installing with admin mode

answered Dec 22, 2021 at 10:53

Guru Prasad's user avatar

The problem, as was noted previously in comments, is the docx module was not compatible with Python 3. It was fixed in this pull-request on github: https://github.com/mikemaccana/python-docx/pull/67

Since the exception is now built-in, the solution is to not import it.

docx.py
@@ -27,7 +27,12 @@
 except ImportError:
     TAGS = {}

-from exceptions import PendingDeprecationWarning
+# Handle PendingDeprecationWarning causing an ImportError if using Python 3
+try:
+    from exceptions import PendingDeprecationWarning
+except ImportError:
+    pass
+
 from warnings import warn

 import logging

dsh's user avatar

dsh

12k3 gold badges33 silver badges51 bronze badges

answered Aug 24, 2015 at 11:46

Dmitry's user avatar

0

You need to make it work with python3.

                     sudo pip3 install python-docx

This installation worked for me in Python3 without any further additions.

             python3
             >> import docx

PS: Note that the ‘pip install python-docx’ or apt-get python3-docx are not useful.

answered Apr 5, 2020 at 14:15

Shagun's user avatar

1

I had the same problem, after installing docx module, got a bunch of errors regarding docx, .oxml and lxml…seems that for my case the package was installed in this folder:

C:Program FilesPython3.7Libsite-packages

and I moved it one step back, to:

C:Program FilesPython3.7Lib

and this solved the issue.

Salio's user avatar

Salio

1,02010 silver badges20 bronze badges

answered Jun 27, 2022 at 19:13

alex's user avatar

python imports exceptions module by itself
comment out import line. it worked for me.

answered Dec 5, 2022 at 18:55

VaibhavP's user avatar

1

I am trying something relatively simple but getting this error:

Error: ImportError: No module named docx

Here is my nodeJS script:

const python = require('python-shell');

const shell = new python('../Python/test.py');

let names = ['Hubert', 'Rupert', 'Sherbert', 'Wubbert', 'Paul'];

shell.send(JSON.stringify(names));

shell.on('message', message => console.log(message));

shell.end(message => {console.log(message)});

the python script «test.py»:

import sys, json
from docx import Document

names = json.loads(sys.stdin.readlines()[0])
document = Document('test.docx')

for name in names:
    for paragraph in document.paragraphs:
        if '$$Name$$' in paragraph.text:
            paragraph.text = name
            document.save(name+'.docx')

print('completed')

The test.docx is a blank word file that has «$$Name$$» written at the top.

Any ideas? When I run any tests in pyCharm using docx it works fine and does not provide this error. Only when I call through python-shell in my node script.

I have tried setting the options like this:

const python = require('python-shell');

let options = {
    pythonPath : '/usr/local/bin/python3'
};

python.defaultOptions = options;

const shell = new python('../Python/test.py');

// rest of code is the same

I verified that this path is where python3 is located on my mac

I have had no luck using these options. All this does is provide a similar error:
Error: docx.opc.exceptions.PackageNotFoundError: Package not found at 'test.docx

@scanny I followed this but did not help. Any idea?

C:Usersx>pip uninstall docx
Cannot uninstall requirement docx, not installed

C:Usersx>pip install python-docx
Requirement already satisfied: python-docx in c:python36libsite-packages
Requirement already satisfied: lxml>=2.3.2 in c:python36libsite-packages (from python-docx)

C:Usersx>python
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32
Type «help», «copyright», «credits» or «license» for more information.

from docx import Document
Traceback (most recent call last):
File «», line 1, in
File «C:Python36libsite-packagesdocx_init_.py», line 3, in
from docx.api import Document # noqa
File «C:Python36libsite-packagesdocxapi.py», line 14, in
from docx.package import Package
File «C:Python36libsite-packagesdocxpackage.py», line 11, in
from docx.opc.package import OpcPackage
File «C:Python36libsite-packagesdocxopcpackage.py», line 12, in
from .part import PartFactory
File «C:Python36libsite-packagesdocxopcpart.py», line 12, in
from .oxml import serialize_part_xml
File «C:Python36libsite-packagesdocxopcoxml.py», line 12, in
from lxml import etree
ImportError: DLL load failed: The specified procedure could not be found.
`

Уведомления

  • Начало
  • » Python для новичков
  • » Ошибка импорта

#1 Июль 22, 2015 21:51:24

Ошибка импорта

Установил python-docx.
Написал такой код:

#!/usr/bin/python3
from docx import Document as docx_parser
doc_obj=docx_parser('/home/pete/work/orig all - ru.docx')
doc_text='nn'.join([paragraph.text for paragraph in doc_obj.paragraphs])

Почему

Python 3.4.2 (default, Oct  8 2014, 13:14:40) 
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from docx import Document as docx_parser

проходит, а при попытке запустить код из файла (tst100.py) я получаю

Traceback (most recent call last):
  File "./tst100.py", line 3, in <module>
    from docx import Document as docx_parser
ImportError: cannot import name 'Document'

?

Отредактировано vanvanov (Июль 22, 2015 22:04:09)

Офлайн

  • Пожаловаться

#2 Июль 22, 2015 23:08:26

Ошибка импорта

Вот что интересно: python-docx обновил свой API, теперь вместо старого

from docx import opendocx as docx_parser

должно быть

from docx import Document as docx_parser

Однако, из питоновской консоли работает только новый импорт (Document), а из программы — только старый (opendocx)! Как мне везде обеспечить работу нового API?

Устанавливал python-docx я с помощью sudo python3 setup.py install. Система Debian Jessie.

Отредактировано vanvanov (Июль 22, 2015 23:09:10)

Офлайн

  • Пожаловаться

#3 Июль 22, 2015 23:27:27

Ошибка импорта

vanvanov
Проверяйте версии модуля который работает в коде и в консоли.

_________________________________________________________________________________
полезный блог о python john16blog.blogspot.com

Офлайн

  • Пожаловаться

#4 Июль 23, 2015 00:11:13

Ошибка импорта

JOHN_16
vanvanovПроверяйте версии модуля который работает в коде и в консоли.

Согласно pkg_resources, и в консоли, и отдельно работают python-docx 0.8.5 (а не устаревший docx).

Офлайн

  • Пожаловаться

#5 Июль 23, 2015 05:30:49

Ошибка импорта

В общем то имелось ввиду:

import docx
print(docx.__version__)

А случаем рядом с вашим файлом нету других docx.py файлов или тп?

_________________________________________________________________________________
полезный блог о python john16blog.blogspot.com

Офлайн

  • Пожаловаться

#6 Июль 23, 2015 05:45:22

Ошибка импорта

JOHN_16
А случаем рядом с вашим файлом нету других docx.py файлов или тп?

Да, действительно, в /usr/local/bin лежал docx.py. Обидно, ведь про это я уже нагуглил, но не придал этому значения, поскольку забыл, что раньше уже пытался установить этот модуль. Теперь работает, спасибо.

Офлайн

  • Пожаловаться

Возможно, вам также будет интересно:

  • Import cv2 python ошибка
  • Immergas eolo star коды ошибок 11
  • Import could not be resolved pylance ошибка
  • Immergas eolo mythos 24 4r ошибка e20
  • Import android support v7 app appcompatactivity ошибка

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии