[Tutor] Working with files with python (gtk)

Tim Golden mail at timgolden.me.uk
Thu Mar 15 11:16:40 CET 2007


Edward A Robinson wrote:
> I guess what Im looking for is a python command that dose what the
> file command in the shell would do
> 
> On 3/14/07, Edward A Robinson <earobinson at gmail.com> wrote:
>> This is my first time posting to the python tutor so be nice, I have
>> read the mailing list and cant seem to find and answer there or on
>> google so I turn to you guys for help. I'm working on a gtk
>> application and I want to list all the image files in a directory. Now
>> I know that if I have an image lets say foo.png and I rename that to
>> foo.txt nautilus (the default gnome browser) still recognizes that
>> file as an image.
>>
>> How can I do the same thing? As well as recognizes images I want users
>> to be able to open up each image with that images default editor. So
>> foo.png may open with eye of gnome but bar.jpg may open with gimp. (If
>> those where the settings in nautilus)

I'm a Windows person rather than a Linux one, so treat this
suggestion with the contempt it deserves ;) I seem to remember
that Nautilus has some kind of Python interface which perhaps
could be used here to ask it what it would do with file x.y.
If not, then your next best is to fall back to some system-specific
mime-type lookup but I presume that would work on extensions, not
on contents. Failing that, you could call the "file" system
command (if that's what it's called) which presumably sniffs
the header and returns something useful.

Basically, knowing the file type comes down to extension or
contents. Python has the mimetypes module for the former. If
it's just images you're after then the Python Imaging Library
(http://effbot.org/zone/pil-index.htm) seems to be able to
read image types correctly, regardless of extension, so maybe
that's a way to go.

<dump>
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on 
win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> import Image
 >>> Image.open ("issue1.jpg").info
{'jfif_version': (1, 1), 'jfif': 257, 'jfif_unit': 0, 'jfif_density': 
(1, 1)}
 >>>
 >>> Image.open ("issue1.xxx").info
{'jfif_version': (1, 1), 'jfif': 257, 'jfif_unit': 0, 'jfif_density': 
(1, 1)}
 >>>
</dump>

TJG


More information about the Tutor mailing list