Platforms: Windows 7/Mac OS X
ActiveState Python 2.7.2

Installed docx on Windows 7 at D:\Program Files (x86)\Python27\Lib\site-packages.
Installed docx on OS X at /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages

Following is the sample script (named as, which runs absolutely fine on the python interpreter:

#!/usr/bin/env python
This file makes an docx (Office 2007) file from scratch, showing off most of python-docx's features.

If you need to make documents from scratch, use this file as a basis for your work.

Part of Python's docx module -
See LICENSE for licensing information.
from docx import *

if __name__ == '__main__':        
    # Default set of relationshipships - these are the minimum components of a document
    relationships = relationshiplist()

    # Make a new document tree - this is the main part of a Word document
    document = newdocument()

    # This xpath location is where most interesting content lives 
    docbody = document.xpath('/w:document/w:body', namespaces=nsprefixes)[0]

    # Append two headings and a paragraph
    docbody.append(heading('''Welcome to Python's docx module''',1)  )   
    docbody.append(heading('Make and edit docx in 200 lines of pure Python',2))
    docbody.append(paragraph('The module was created when I was looking for a Python support for MS Word .doc files on PyPI and Stackoverflow. Unfortunately, the only solutions I could find used:'))

    # Add a numbered list
    for point in ['''COM automation''','''.net or Java''','''Automating OpenOffice or MS Office''']:
    docbody.append(paragraph('''For those of us who prefer something simpler, I made docx.''')) 

    docbody.append(heading('Making documents',2))
    docbody.append(paragraph('''The docx module has the following features:'''))

    # Add some bullets
    for point in ['Paragraphs','Bullets','Numbered lists','Multiple levels of headings','Tables','Document Properties']:

    docbody.append(paragraph('Tables are just lists of lists, like this:'))
    # Append a table

    docbody.append(heading('Editing documents',2))
    docbody.append(paragraph('Thanks to the awesomeness of the lxml module, we can:'))
    for point in ['Search and replace','Extract plain text of document','Add and delete items anywhere within the document']:

    # Search and replace
    print 'Searching for something in a paragraph ...',
    if search(docbody, 'the awesomeness'): print 'found it!'
    else: print 'nope.'

    print 'Searching for something in a heading ...',
    if search(docbody, '200 lines'): print 'found it!'
    else: print 'nope.'

    print 'Replacing ...',
    docbody = replace(docbody,'the awesomeness','the goshdarned awesomeness') 
    print 'done.'

    # Add a pagebreak
    docbody.append(pagebreak(type='page', orient='portrait'))

    docbody.append(heading('Ideas? Questions? Want to contribute?',2))
    docbody.append(paragraph('''Email <>'''))

    # Create our properties, contenttypes, and other support files
    coreprops = coreproperties(title='Python docx demo',subject='A practical example of making docx from Python',creator='Mike MacCana',keywords=['python','Office Open XML','Word'])
    appprops = appproperties()
    contenttypes = contenttypes()
    websettings = websettings()
    wordrelationships = wordrelationships(relationships)

    # Save our document

Following is the setup script (named as to create the standalone (.app in Mac OSX and .exe in Windows 7):

import sys,os

# Globals: START
# Globals: STOP

# Global Functions: START
def isDarwin():
    return sys.platform=='darwin'

def isLinux():
    return sys.platform=='linux2'

def isWindows():
# Global Functions: STOP

if isDarwin():
    from setuptools import setup

    # Setup distribution directory: START
    dist_dir=os.path.abspath('%s/osx' %(dist_dir_main_path))
    if os.path.exists(dist_dir):
        os.system('rm -rf %s' %(dist_dir))
    os.system('mkdir -p %s' %(dist_dir))
    # Setup distribution directory: STOP

    APP = ['' %(main_script)]
    OPTIONS={'argv_emulation': False,
             'dist_dir': dist_dir,
             'includes': includes_list
    print 'Creating standalone now...'
    setup(app=APP,options={'py2app': OPTIONS},setup_requires=['py2app'])
    os.system('rm -rf build')
    os.system('tar -C %s -czf %s/%s.tgz' %(dist_dir,dist_dir,main_script,main_script))
    os.system('rm -rf %s/' %(dist_dir,main_script))    
    print 'Re-distributable Standalone file(s) created at %s/ Unzip and start using!!!' %(dist_dir,main_script)    

elif isWindows():
    from distutils.core import setup
    import py2exe

    # Setup distribution directory: START
    dist_dir=os.path.abspath('%s/win' %(dist_dir_main_path))
    if os.path.exists(dist_dir):
        os.system('rmdir /S /Q %s' %(dist_dir))
    os.system('mkdir %s' %(dist_dir))
    # Setup distribution directory: STOP

    OPTIONS={'compressed': compression_level,
             'optimize': optimization_level,
             'bundle_files': bundle_parameter,
             'dist_dir': dist_dir,
             'xref': module_cross_reference_parameter,
             'skip_archive': skip_archive_parameter,
             'ascii': ascii_parameter,
             'custom_boot_script': '',
             'includes': includes_list
    print 'Creating standalone now...'
    setup(options = {'py2exe': OPTIONS},zipfile = None,windows=[{'script': '' %(main_script)}])
    print 'Re-distributable Standalone file(s) created in the following location: %s' %(dist_dir)
    os.system('rmdir /S /Q build')

Now comes the real problem.

Following is the error posted on Mac OS X console after trying to use the, created using the command python py2app:

docx_example: Searching for something in a paragraph ... found it!
docx_example: Searching for something in a heading ... found it!
docx_example: Replacing ... done.
docx_example: Traceback (most recent call last):
docx_example:   File "/Users/admin/docx-bin/osx/", line 64, in <module>
docx_example:     _run('')
docx_example:   File "/Users/admin/docx-bin/osx/", line 36, in _run
docx_example:     execfile(path, globals(), globals())
docx_example:   File "/Users/admin/docx-bin/osx/", line 75, in <module>
docx_example:     savedocx(document,coreprops,appprops,contenttypes,websettings,wordrelationships,'docx_example.docx')
docx_example:   File "docx.pyc", line 849, in savedocx
docx_example: AssertionError
docx_example: docx_example Error
docx_example Exited with code: 255

Following is the error posted in docx_example.exe.log file in Windows 7 after trying to use the docx_example.exe, created using the command python py2exe:

Traceback (most recent call last):
      File "", line 75, in <module>
      File "docx.pyo", line 854, in savedocx
    WindowsError: [Error 3] The system cannot find the path specified: 'D:\\docx_example\\docx_example.exe\\template'

As you can see, both OS X and Windows 7 are referring to something similar here. Please help.

Re: py2exe/py2app and docx don't work together 80 80

i dnt kno where the problem is but if you want make py files to exe u could try cx freeze

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.