docx.opc.exceptions.PackageNotFoundError: Package not found at

Django Girl picture Django Girl · Nov 9, 2017 · Viewed 7.3k times · Source

Can't open doxc file by path (Package not found at...)

View of directory:

enter image description here

Code:

from docx import Document

# some path of file:
path = 'TestDir/dir2/doc22.docx'

# open docx file:
doc = Document(path)

Have this:

Traceback (most recent call last):
  File "T23_7.py", line 73, in <module>
    searchRegex(dirName, regex)
  File "T23_7.py", line 57, in searchRegex
    current_doc = Document(docx_file)
  File "/home/ch_dmitriy/Documents/Projects/Tutorials/mech-mat-homework/env/lib/python3.5/site-packages/docx/api.py", line 25, in Document
    document_part = Package.open(docx).main_document_part
  File "/home/ch_dmitriy/Documents/Projects/Tutorials/mech-mat-homework/env/lib/python3.5/site-packages/docx/opc/package.py", line 116, in open
    pkg_reader = PackageReader.from_file(pkg_file)
  File "/home/ch_dmitriy/Documents/Projects/Tutorials/mech-mat-homework/env/lib/python3.5/site-packages/docx/opc/pkgreader.py", line 32, in from_file
    phys_reader = PhysPkgReader(pkg_file)
  File "/home/ch_dmitriy/Documents/Projects/Tutorials/mech-mat-homework/env/lib/python3.5/site-packages/docx/opc/phys_pkg.py", line 31, in __new__
    "Package not found at '%s'" % pkg_file
docx.opc.exceptions.PackageNotFoundError: Package not found at 'TestDir/dir2/doc22.docx'

Help, please.

Answer

scanny picture scanny · Nov 9, 2017

This error simply means there is no .docx file at the location you specified.

Since you specified a relative path, the actual path used is determined by adding 'TestDir/dir2/doc22.docx' to the current working directory Python is using at run time.

You can discover the path being used with this short code snippet:

import os
print(os.path.abspath('TestDir/dir2/doc22.docx')

I expect you'll find that it prints out a path that does not exist, and that you'll need to modify the path string you give it to point to the right place.

Worst case, you can specify an absolute path, like /home/ch_dmitriy/Documents/Projects/Tutorials/TestDir/dir2/doc22.docx.