Extract and Parse ODF Files with Python
Listing 2. List the Files in the ODT Archive
import sys, zipfile myfile = zipfile.ZipFile(sys.argv[1]) listoffiles = myfile.infolist() for s in listoffiles: print s.orig_filename
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.
Listing 3. Extracting Files for the ODT Archive
import sys, zipfile
if len(sys.argv) < 2:
print "Usage: extract odf-filename outputfilename
sys.exit(0)
myfile = zipfile.ZipFile(sys.argv[1])
listoffiles = myfile.infolist()
for s in listoffiles:
if s.orig_filename == 'META-INF/manifest.xml':
fd = open(sys.argv[2],'w')
bh = myfile.read(s.orig_filename)
fd.write(bh)
fd.close()
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).
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
- Dynamic DNS—an Object Lesson in Problem Solving
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Using Salt Stack and Vagrant for Drupal Development
- New Products
- A Topic for Discussion - Open Source Feature-Richness?
- Drupal Is a Framework: Why Everyone Needs to Understand This
- Validate an E-Mail Address with PHP, the Right Way
- RSS Feeds
- Readers' Choice Awards
- Tech Tip: Really Simple HTTP Server with Python
- DynDNS
3 hours 3 min ago - Reply to comment | Linux Journal
3 hours 36 min ago - All the articles you talked
5 hours 59 min ago - All the articles you talked
6 hours 3 min ago - All the articles you talked
6 hours 4 min ago - myip
10 hours 29 min ago - Keeping track of IP address
12 hours 20 min ago - Roll your own dynamic dns
17 hours 33 min ago - Please correct the URL for Salt Stack's web site
20 hours 44 min ago - Android is Linux -- why no better inter-operation
23 hours 16 sec ago
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?




Comments
File is not a zip file
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!
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
lpod is an ODF library that allow to easily manipulate ODF documents.
Fail? What fail?
To the first commenter, win32 doesn't mean windows 3.2. It means 32-bit windows.
(Windows NT/2000/XP/Vista/7)
FAIL!
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
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
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
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.