seperating directories from files

R

raj

i'm surely a newbie in python and on the go, I just tried to write a
small app to change the gnome desktop background daily. It's working
now making use of listdir() to find the contents of each dir I
encounter. But I'm sure that my code won't go that smooth forever.

How can I find if the content is a Directory or not and if it's a file,
whether it is an image file or not?
Is there any method to read the metadata of files?
Thanking all of you in advance.....
 
F

Fuzzyman

For checking the contents of a directory :

for entry in os.listdir(this_dir):
if os.path.isdir(os.path.join(this_dir, entry));
continue

You could use splitext to get the extension of a the filename, and
*assume* that '.jpg', '.png', '.ico' and friends are images.

I'm sure PIL will have ways of checking image metadata (if this is all
you are specifically after here).

All the best,


Fuzzyman
http://www.voidspace.org.uk/python/index.shtml
 
R

raj

Thanx adam 'n' fuzzyman! got that 'isdir'. But how the other thing?
Can't find anything suitable. I'll be happy on getting atleast
something like the file command in Unix
 
J

John Zenger

raj said:
How can I find ... if it's a file,
whether it is an image file or not?

Assuming you are running on an operating system that uses file
extensions to indicate a file is an image (like Windows or Linux),
something like this will work:

import os.path

def isImage(filename):
return os.path.splitext(filename)[1] in ['.jpg','.png','.gif']

(Add as many file extensions to that list as you like...)
Is there any method to read the metadata of files?

It's not what you are looking for here, but os.stat gives you access to
lots of information about files. In Linux and Windows, though, the
'type' of a file is incorporated into its filename through an extension.
 
D

Diez B. Roggisch

It's not what you are looking for here, but os.stat gives you access to
lots of information about files. In Linux and Windows, though, the
'type' of a file is incorporated into its filename through an extension.

No, only in windows. Under linux/unix in general there might exist the
file-command, which is basically a heuristic approach to the problem by
scanning for magic numbers and the like. Should be installed on any decent
system.

I'm not aware of a wrapping of "file" for python, and as the search terms
are pretty non-descriptive a quick google search hasn't enlightend me. But
you could always go for subprocess and invoke file, of course.

Diez
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,283
Messages
2,571,405
Members
48,098
Latest member
inno vation

Latest Threads

Top