Extract and Parse ODF Files with Python

 in
Use Python to demystify Open Document Format files.

The import statement allows you to use the sys module for getting a command-line argument of the file, and the zipfile module loads in the functionality for reading and unzipping files. As you saw from the Python shell, the infolist() method on the zipfile archive lists the files in it. So iterating over the items from the infolist() and then calling an orig_filename member function gives you a list of all files in the archive.

For more detailed information, try something like this:

print s.orig_filename, s.date_time, s.filename,
 ↪s.file_size, s.compress_size

You will receive more information about the file, quite similar to this:

mimetype (2006, 9, 9, 7, 50, 10) mimetype 39 39
Configurations2/statusbar/ (2006, 9, 9, 7, 50, 10)
Configurations2/statusbar/ 0 0
Configurations2/accelerator/current.xml
 ↪(2006, 9, 9, 7, 50, 10)
Configurations2/accelerator/current.xml 0 2
Configurations2/floater/ (2006, 9, 9, 7, 50, 10)
Configurations2/floater/ 0 0
...SNIPPED FOR BREVITY...

A typical ODF text file (with the .odt extension) will have some of the following files when unzipped. Here's the output:

mimetype
Configurations2/statusbar/
Configurations2/accelerator/current.xml
Configurations2/floater/
Configurations2/popupmenu/
Configurations2/progressbar/
Configurations2/menubar/
Configurations2/toolbar/
Configurations2/images/Bitmaps/
layout-cache
content.xml
styles.xml
meta.xml
Thumbnails/thumbnail.png
settings.xml
META-INF/manifest.xml

The most important file in the archive is the content.xml file, because it contains the data for the document itself. I discuss this file here; however, for detailed information on each tag and so on, take a look at the specification in the 2,000+-page PDF file from the OASIS Web site (see Resources).

Basically, the content.xml file looks like a DHTML file with tags for all the contents. The tag I was concerned with most for my search operation was the <text:p> tag and its closing tag </text:p>, which wraps paragraphs in a document. I'll show you how to get this tag from a content file later in this article.

Other files of interest in the archive are the META-INF/manifest.xml, mimetype, meta.xml and styles.xml. Other files simply contain data for configurations for the word processors reading and displaying the contents file.

The manifest is simply an XML file with a listing of all the files in the zipped archive. The mimetype file is a single line containing the mimetype of the content file. The meta.xml contains information about the author, creation date and so on. The styles file contains all the formatting styles for displaying the file.

You can extract any of these files from the ODF file with the read() method on the zip object to get it as a very long string. Once read, you can modify, view and write the whole string to disk as an independent file. Listing 3 shows how to extract the manifest.xml file.

For more than one file, you can use a list instead of the if clause:

if s.orig_filename in ['content.xml', 'styles.xml']:

This way, you can extract whatever files you need to look at simply by reading in their contents and either manipulating them or writing them off to disk.

The contents of an XML file are best suited for manipulation as a tree structure. Use the XML parsing capabilities in Python to get a tree of all the nodes within an XML file. Once you have the tree in a content file, you easily can get to the <text:p> nodes. You don't really have to extract the file to disk, because you also can run an XML parser on the string just as well as reading from a file.

There are two types of XML parsers, SAX and DOM. The SAX parser is faster but less memory-intensive, because it reads and parses an input file one tag at a time. You have only one tag at a time to work with and must track data yourself. In contrast, the DOM parser reads the entire file into memory and therefore provides better options for navigating and manipulating the XML nodes.

Let's look at examples of using both SAX and DOM, so you can see which one suits your purpose. The SAX example shows how to extract unique node names from an XML file. The DOM example illustrates how to read values from within specific nodes once the file has been read completely into memory.

First, let's use the SAX parser to see what nodes are available in the content.xml file. The code simply prints the name of each type node found in the file. Note that for different types of files you may get different node names (Listing 4).

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

File is not a zip file

hypertex's picture

I am trying to run listing 5. Am I the only one receiving this error?


File "./odt.py", line 13, in __init__
self.m_odf = zipfile.ZipFile(filename)
File "/usr/lib/python2.6/zipfile.py", line 693, in __init__
self._GetContents()
File "/usr/lib/python2.6/zipfile.py", line 713, in _GetContents
self._RealGetContents()
File "/usr/lib/python2.6/zipfile.py", line 725, in _RealGetContents
raise BadZipfile, "File is not a zip file"
zipfile.BadZipfile: File is not a zip file

and yet . . .

>>> odfname = ('bill_of_rights.odt')
>>> zipfile.is_zipfile(odfname)
True

I'm confused is_zipfile() returns true, but I get a BadZipfile exception. Same result with several different files, so I don't think it is a bad file. Running python 2.6.4 on fedora 13.

D'OH!

hypertex's picture

the __main__ block should have:

filename = sys.argv[1]
phrase = sys.argv[2]

I keep forgetting that sys.argv[0] is a reference to the script, not the first argument to the script.

LPOD Project

Anonymous's picture

lpod is an ODF library that allow to easily manipulate ODF documents.

Fail? What fail?

Anonymous's picture

To the first commenter, win32 doesn't mean windows 3.2. It means 32-bit windows.
(Windows NT/2000/XP/Vista/7)

FAIL!

Anonymous's picture

Python 2.4.1 (#65, Mar 30 2005, 09:13:57)
[MSC v.1310 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()"
for more information.

however, very good tutorial doh! ;)

greets
Royma

Nice

Nichoals's picture

Nice tutorials.. You'r the only one in the net that write something aboute odt and python clearly.
Do you have a tutorials to pick pictures from the odt file too?

uçak bileti

uçak bileti's picture

Have read all of the posts. Very interesting and much better disciplined than most sessions. and thank you for information.

Plug-in For MS Office

W^L+'s picture

Instead of the ODF-Converter project on SourceForge, with its well-known flaws (cannot set ODF formats as default formats for MS Office, poor fidelity between original file and the imported/exported version, ODF placed in separate submenu instead of the usual file->save as, and intermediate saves still require long export process), I'd recommend Sun's plugin for MS Office. It features much better integration with MS Office and better fidelity import/export.

Either one will trigger warnings about the format not being fully compatible, but for most purposes, ODF is fully-capable of representing MS Office data.

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix