[Tutor] open files other than text?

Kirby Urner urnerk@qwest.net
Tue, 22 Jan 2002 23:48:40 -0800


At 11:38 PM 1/22/2002 -0500, Ron wrote:
>I have windows 98 Python2.2. Can you open files other than text files. I
>tried to open a .doc file and just got a line of giberish. What kind of
>things can be opened?

Python will open any file, but the question is what do you
do with it then?  You need to poke around in the standard
library, or download additional modules, that let you
mess with file formats of various kinds.

For example, a random search on google brought me to
http://www.dotfunk.com/projects/mp3 as a place to grab a
module for looking the mp3 (sound) file headers.  I just
tested it in the shell:

 >>> mp3.mp3info(r"d:/music/my music/Brian Eno and David Byrne
- My Life in the Bush of Ghosts - 01 - America Is Waiting.mp3")
{'SS': 37, 'STEREO': 1, 'VERSION': 1, 'MODE': 1, 'COPYRIGHT': 1,
'MM': 3, 'FREQUENCY': 44100, 'BITRATE': 128, 'LAYER': 3}

You see it returns a dictionary with lots of info about the
file.  So you could use this in a program.

Fredrik Lundh's Python Imaging Library (PIL) is where you'll
find all kinds of modules for dealing with graphics files,
like GIFs and JPEGs.

If you're using Python 2.2, the relevant PIL is at
http://www.pythonware.com/downloads/index.htm#pil
Python Imaging Library 1.1.2 for Python 2.2b1 (Windows only)

With it, you can do things like:

   >>> import PIL
   >>> help(PIL)

<from reading the response, I learned enought to...>

   >>> from PIL import JpegImagePlugin
   >>> help(JpegImagePlugin)

   >>> from JpegImagePlugin import JpegImageFile
   >>> ojpeg = JpegImageFile(r"E:\INTERNET\DOWNLOAD\worldgame.jpg")
   >>> ojpeg.histogram()
   [619, 248, 240, 278, 298, 264, 273, 227, 208...
   <SNIP>

But when I try to go ojpeg.show(), Windows fusses that the
invoked program wants to run in DOS real mode, which isn't
supported in Windows.  If I do the same in the DOS shell,
however, I'm able to view the image (Python boots some native
viewer).

PIL would let me rotate, crop, and otherwise mess with this
jpeg, all programmatically.  I could write a Python program
to convert an entire directory of pictures to thumbnails
or something like that.

Hope this gives you some idea of what's involved in exploring
other kinds of files.  Thousands of hours go into packages
like PIL, because image files are complicated.  So best to
take advantage of what these experts have made available.

Kirby