By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,877 Members | 1,047 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,877 IT Pros & Developers. It's quick & easy.

newb question: file searching

P: n/a
I'm new at Python and I need a little advice. Part of the script I'm
trying to write needs to be aware of all the files of a certain
extension in the script's path and all sub-directories. Can someone
set me on the right path to what modules and calls to use to do that?
You'd think that it would be a fairly simple proposition, but I can't
find examples anywhere. Thanks.

Aug 8 '06 #1
Share this Question
Share on Google+
29 Replies


P: n/a
Hey, I've done similar things.

You can use system comands with the following

import os
os.system('command here')

You'd maybe want to do something like

dir_name = 'mydirectory'
import os
os.system('ls ' +dir_name + ' lsoutput.tmp')
fin = open('lsoutput.tmp', 'r')
file_list = fin.readlines()
fin.close()

Now you have a list of all the files in dir_name stored in file_list.

Then you'll have to parse the input with string methods. They're easy
in python. Here's the list of them:
http://docs.python.org/lib/string-methods.html

There is probably a better way to get the data from an os.system
command but i haven't figured it out. Instead what i'm doing is
writing the stdio output to a file and reading in the data. It works
fine. Put it in your tmp dir if you're in linux.
ja*******@gmail.com wrote:
I'm new at Python and I need a little advice. Part of the script I'm
trying to write needs to be aware of all the files of a certain
extension in the script's path and all sub-directories. Can someone
set me on the right path to what modules and calls to use to do that?
You'd think that it would be a fairly simple proposition, but I can't
find examples anywhere. Thanks.
Aug 8 '06 #2

P: n/a
Hey, I've done similar things.

You can use system comands with the following

import os
os.system('command here')

You'd maybe want to do something like

dir_name = 'mydirectory'
import os
os.system('ls ' +dir_name + ' lsoutput.tmp')
fin = open('lsoutput.tmp', 'r')
file_list = fin.readlines()
fin.close()

Now you have a list of all the files in dir_name stored in file_list.

Then you'll have to parse the input with string methods. They're easy
in python. Here's the list of them:
http://docs.python.org/lib/string-methods.html

There is probably a better way to get the data from an os.system
command but i haven't figured it out. Instead what i'm doing is
writing the stdio output to a file and reading in the data. It works
fine. Put it in your tmp dir if you're in linux.
ja*******@gmail.com wrote:
I'm new at Python and I need a little advice. Part of the script I'm
trying to write needs to be aware of all the files of a certain
extension in the script's path and all sub-directories. Can someone
set me on the right path to what modules and calls to use to do that?
You'd think that it would be a fairly simple proposition, but I can't
find examples anywhere. Thanks.
Aug 8 '06 #3

P: n/a

ja*******@gmail.com wrote:
I'm new at Python and I need a little advice. Part of the script I'm
trying to write needs to be aware of all the files of a certain
extension in the script's path and all sub-directories.
What you want is os.walk().

http://www.python.org/doc/current/lib/os-file-dir.html

Aug 8 '06 #4

P: n/a
ja*******@gmail.com wrote:
I'm new at Python and I need a little advice. Part of the script I'm
trying to write needs to be aware of all the files of a certain
extension in the script's path and all sub-directories. Can someone
set me on the right path to what modules and calls to use to do that?
You'd think that it would be a fairly simple proposition, but I can't
find examples anywhere. Thanks.
dir_name = 'mydirectory'
extension = 'my extension'
import os
files = os.listdir(dir_name)
files_with_ext = [file for file in files if file.endswith(extension)]

That will only do the top level (not subdirectories), but you can use
the os.walk procedure (or some of the other procedures in the os and
os.path modules) to do that.

--Dave

Aug 8 '06 #5

P: n/a
Mike Kent wrote:
What you want is os.walk().

http://www.python.org/doc/current/lib/os-file-dir.html
I'm thinking os.walk() could definitely be a big part of my solution,
but I need a little for info. If I'm reading this correctly, os.walk()
just goes file by file and serves it up for your script to decide what
to do with each one. Is that right? So, for each file it found, I'd
have to decide if it met the criteria of the filetype I'm searching for
and then add that info to whatever datatype I want to make a little
list for myself? Am I being coherent?

Something like:

for files in os.walk(top, topdown=False):
for name in files:
(do whatever to decide if criteria is met, etc.)

Does this look correct?

Aug 8 '06 #6

P: n/a
I'm thinking os.walk() could definitely be a big part of my solution,
but I need a little for info. If I'm reading this correctly, os.walk()
just goes file by file and serves it up for your script to decide what
to do with each one. Is that right? So, for each file it found, I'd
have to decide if it met the criteria of the filetype I'm searching for
and then add that info to whatever datatype I want to make a little
list for myself? Am I being coherent?

Something like:

for files in os.walk(top, topdown=False):
for name in files:
(do whatever to decide if criteria is met, etc.)

Does this look correct?
IIRC, repeated calls to os.walk would implement a depth-first search on
your current directory. Each call returns a list:
[<directory name relative to where you started>, <list of files and
directories in that directory>]

--dave

Aug 8 '06 #7

P: n/a
Thanks, Dave. That's exactly what I was looking for, well, except for
a few small alterations I'll make to achieve the desired effect. I
must ask, in the interest of learning, what is

[file for file in files if file.endswith(extension)]

actually doing? I know that 'file' is a type, but what's with the set
up and the brackets and all? Can someone run down the syntax for me on
that? And also, I'm still not sure I know exactly how os.walk() works.
And, finally, the python docs all note that symbols like . and ..
don't work with these commands. How can I grab the directory that my
script is residing in?

Thanks.
hiaips wrote:
ja*******@gmail.com wrote:
I'm new at Python and I need a little advice. Part of the script I'm
trying to write needs to be aware of all the files of a certain
extension in the script's path and all sub-directories. Can someone
set me on the right path to what modules and calls to use to do that?
You'd think that it would be a fairly simple proposition, but I can't
find examples anywhere. Thanks.

dir_name = 'mydirectory'
extension = 'my extension'
import os
files = os.listdir(dir_name)
files_with_ext = [file for file in files if file.endswith(extension)]

That will only do the top level (not subdirectories), but you can use
the os.walk procedure (or some of the other procedures in the os and
os.path modules) to do that.

--Dave
Aug 8 '06 #8

P: n/a

ja*******@gmail.com wrote:
Mike Kent wrote:
What you want is os.walk().

http://www.python.org/doc/current/lib/os-file-dir.html

I'm thinking os.walk() could definitely be a big part of my solution,
but I need a little for info. If I'm reading this correctly, os.walk()
just goes file by file and serves it up for your script to decide what
to do with each one. Is that right? So, for each file it found, I'd
have to decide if it met the criteria of the filetype I'm searching for
and then add that info to whatever datatype I want to make a little
list for myself? Am I being coherent?

Something like:

for files in os.walk(top, topdown=False):
for name in files:
(do whatever to decide if criteria is met, etc.)

Does this look correct?
Not completely. According to the documentation, os.walk returns a
tuple:
(directory, subdirectories, files)
So the files you want are in the third element of the tuple.

You can use the fnmatch module to find the names that match your
filename pattern.

You'll want to do something like this:
>>for (dir, subdirs, files) in os.walk('.'):
.... for cppFile in fnmatch.filter(files, '*.cpp'):
.... print cppFile
....
ActiveX Test.cpp
ActiveX TestDoc.cpp
ActiveX TestView.cpp
MainFrm.cpp
StdAfx.cpp
>>>
Please note that your results will vary, of course.

Aug 8 '06 #9

P: n/a

ja*******@gmail.com wrote:
Thanks, Dave. That's exactly what I was looking for, well, except for
a few small alterations I'll make to achieve the desired effect. I
must ask, in the interest of learning, what is

[file for file in files if file.endswith(extension)]

actually doing? I know that 'file' is a type, but what's with the set
up and the brackets and all? Can someone run down the syntax for me on
that? And also, I'm still not sure I know exactly how os.walk() works.
And, finally, the python docs all note that symbols like . and ..
don't work with these commands. How can I grab the directory that my
script is residing in?
[file for file in files if file.endswith(extension)] is called a list
comprehension. Functionally, it is equivalent to something like this:
files_with_ext = []
for file in files:
if file.endswith(extension):
files_with_ext.append(file)
However, list comprehensions provide a much more terse, declarative
syntax without sacrificing readability.

To get your current working directory (i.e., the directory in which
your script is residing):
cwd = os.getcwd()

As far as os.walk...
This is actually a generator (effectively, a function that eventually
produces a sequence, but rather than returning the entire sequence, it
"yields" one value at a time). You might use it as follows:
for x in os.walk(mydirectory):
for file in x[1]:
<whatever tests or code you need to run>

You might want to read up on the os and os.path modules - these
probably have many of the utilities you're looking for.

Good luck,
dave

Aug 8 '06 #10

P: n/a
Oops, what I wrote above isn't quite correct. As another poster pointed
out, you'd want to do
for file in x[2]:
....

--dave

Aug 8 '06 #11

P: n/a
So far, so good. I just have a few more questions.

Here's my code so far:

import os
top = '/home/USERNAME/'
images = []
for files in os.walk(top, topdown=True):
images += [file for file in files[2] if file.endswith('jpg')]
print images

I still need to know how I can dynamically get the name of the
directory that my script is in. Also, how can I get it to add the full
path of the file to "images" instead of just the file name. See, when
I go to use a particular image name later on, it won't do me much good
if I don't have the path to it.

Aug 8 '06 #12

P: n/a
ja*******@gmail.com wrote:
hiaips wrote:
ja*******@gmail.com wrote:
I'm new at Python and I need a little advice. Part of the script I'm
trying to write needs to be aware of all the files of a certain
extension in the script's path and all sub-directories. Can someone
set me on the right path to what modules and calls to use to do that?
You'd think that it would be a fairly simple proposition, but I can't
find examples anywhere. Thanks.
dir_name = 'mydirectory'
extension = 'my extension'
import os
files = os.listdir(dir_name)
files_with_ext = [file for file in files if file.endswith(extension)]

That will only do the top level (not subdirectories), but you can use
the os.walk procedure (or some of the other procedures in the os and
os.path modules) to do that.

--Dave

Thanks, Dave. That's exactly what I was looking for, well, except for
a few small alterations I'll make to achieve the desired effect. I
must ask, in the interest of learning, what is

[file for file in files if file.endswith(extension)]

actually doing? I know that 'file' is a type, but what's with the set
up and the brackets and all? Can someone run down the syntax for me on
that? And also, I'm still not sure I know exactly how os.walk() works.
And, finally, the python docs all note that symbols like . and ..
don't work with these commands. How can I grab the directory that my
script is residing in?

Thanks.

'file' *is* the name of the file type, so one shouldn't reuse it as the
name of a variable as Dave did in his example.

the brackets are a "list comprehension" and they work like so:

files_with_ext = []
for filename in files:
if filename.endswith(extension):
files_with_ext.append(filename)

The above is exactly equivalent to the [filename for filename in
files... ] form.

AFAIK, os.listdir('.') works fine, but you can also use
os.listdir(os.getcwd()). However, both of those return the current
directory, which can be different than the directory your script's
residing in if you've called os.chdir() or if you start your script
from a different directory.
HTH.

(Also, if you're not already, be aware of os.path.isfile() and
os.path.isdir(). They should probably be helpful to you.)

Peace,
~Simon

Aug 8 '06 #13

P: n/a

ja*******@gmail.com wrote:
I must ask, in the interest of learning, what is

[file for file in files if file.endswith(extension)]

actually doing? I know that 'file' is a type, but what's with the set
up and the brackets and all?
Other people explained the list comprehension, but you might be
confused about the unfortunate choice of 'file' as the name in this
example. 'file' is a built-in as you remarked. It is allowed, but a bad
idea, to use names that are the same as built-ins. Some people
characterize this as shadowing the built-in.

A similar, common case is when people use the name 'list' for a list
object. They shouldn't.

The example could have been written as:

[f for f in files if f.endswith(extension)]

Aug 8 '06 #14

P: n/a
Okay. This is almost solved. I just need to know how to have each
entry in my final list have the full path, not just the file name.
Also, I've noticed that files are being found within hidden
directories. I'd like to exclude hidden directories from the walk, or
at least not add anything within them. Any advice?

Here's what I've got so far:

def getFileList():
import os
imageList = []
for files in os.walk(os.getcwd(), topdown=True):
imageList += [file for file in files[2] if file.endswith('jpg') or
file.endswith('gif')]
return imageList

Aug 8 '06 #15

P: n/a
At Tuesday 8/8/2006 17:55, ja*******@gmail.com wrote:
>I must ask, in the interest of learning, what is

[file for file in files if file.endswith(extension)]

actually doing? I know that 'file' is a type, but what's with the set
up and the brackets and all? Can someone run down the syntax for me on
that?
Note: "file" is really a bad name here; rebinding builtins is never a
good idea. But unfortunately names like "file", "dir", "dict" are
very handy when you need a dummy variable like this, so people tend
to use them.
This has exactly the same meaning:

[x for x in files if x.endswith(extension)]

>I still need to know how I can dynamically get the name of the
directory that my script is in.
os.path.dirname(os.path.abspath(sys.modules[__name__].__file__))
>Also, how can I get it to add the full
path of the file to "images" instead of just the file name. See, when
I go to use a particular image name later on, it won't do me much good
if I don't have the path to it.
Look at os.path.join()

Gabriel Genellina
Softlab SRL

__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Aug 8 '06 #16

P: n/a
ja*******@gmail.com wrote:
And, finally, the python docs all note that symbols like . and ..
don't work with these commands.
Where did you read that? The docs for os.listdir do say that '.' and
'..' are (sensibly) not returned as *results*. AFAIK there is nothing
to stop you using '.' or '..' as a path *argument* where
appropriate/useful.
How can I grab the directory that my
script is residing in?
C:\junk>type scriptdir.py
import sys, os.path
scriptpath = sys.argv[0] # read the docs for sys.argv
print "script is", scriptpath
scriptdir = os.path.split(scriptpath)[0] # read the docs for
os.path.split
print "script lives in", scriptdir
C:\junk>scriptdir.py
script is C:\junk\scriptdir.py
script lives in C:\junk

C:\junk>move scriptdir.py \bin

C:\junk>scriptdir.py
script is c:\bin\scriptdir.py
script lives in c:\bin

[Curiosity: drive letter is upper-case in first example, lower in
second]

HTH,
John

Aug 8 '06 #17

P: n/a
ja*******@gmail.com wrote:
Okay. This is almost solved. I just need to know how to have each
entry in my final list have the full path, not just the file name.
from http://docs.python.org/lib/os-file-dir.html:

walk() generates the file names in a directory tree, by walking the
tree either top down or bottom up. For each directory in the tree
rooted at directory top (including top itself), it yields a 3-tuple
(dirpath, dirnames, filenames).

dirpath is a string, the path to the directory. dirnames is a list of
the names of the subdirectories in dirpath (excluding '.' and '..').
filenames is a list of the names of the non-directory files in dirpath.
Note that the names in the lists contain no path components. To get a
full path (which begins with top) to a file or directory in dirpath, do
os.path.join(dirpath, name).

--------

So walk yields a 3-tuple, not just a filename. You seem to be somewhat
aware of this where you refer to files[2] in your list comprehension,
but I believe that is not constructed correctly.

Try this (untested):

def get_image_filepaths(target_folder):
"""Return a list of filepaths (path plus filename) for all images
in target_folder or any subfolder"""
import os
images = []
for dirpath, dirnames, filenames in os.walk(target_folder):
for filename in filenames:
normalized_filename = filename.lower()
if normalized_filename.endswith('.jpg') or
normalized_filename.endswith('.gif'):
filepath = os.path.join(dirpath, filename)
images.append(filepath)
return images

import os
images = get_image_filepaths(os.getcwd())
Also, I've noticed that files are being found within hidden
directories. I'd like to exclude hidden directories from the walk, or
at least not add anything within them. Any advice?
Decide how you identify a hidden directory and test dirpath before
adding it to the images list. E.g., test whether dirpath starts with
'.' and skip it if so.
>
Here's what I've got so far:

def getFileList():
import os
imageList = []
for files in os.walk(os.getcwd(), topdown=True):
imageList += [file for file in files[2] if file.endswith('jpg') or
file.endswith('gif')]
return imageList
Aug 8 '06 #18

P: n/a
Also, I've noticed that files are being found within hidden
directories. I'd like to exclude hidden directories from the walk, or
at least not add anything within them. Any advice?
The second item in the tuple yielded by os.walk() is a list of
subdirectories inside the directory indicated by the first item in the
tuple. You can remove values from this list at runtime to have os.walk
skip over them.

Aug 8 '06 #19

P: n/a
ja*******@gmail.com wrote:
[...]
that? And also, I'm still not sure I know exactly how os.walk() works.
And, finally, the python docs all note that symbols like . and ..
don't work with these commands. How can I grab the directory that my
script is residing in?
os.getcwd() will get you the directory your script is in (at least as
long as you're running the script from the current directory :-)

Here's my version of how to it (comments below):

def collect_ext(*extensions):
"""Return a list of files from current directory and downwards
that have given extensions. Call it like collect_ext('.py',
'.pyw')
"""
res = []
for dirname, _, files in os.walk(os.getcwd()):
for fname in files:
name, ext = os.path.splitext(fname)
if ext in extensions:
res.append(os.path.join(dirname, fname))
return res

Each time around the outer for-loop, os.walk() gives us all the
filenames (as a list into the files variable) in a sub-directory. We
need to run through this list (inner for-loop), and save all files with
one of the right extensions. (os.walk() also gives us a list of all
subdirectories, but since we don't need it, I map it to the _ (single
underscore) variable which is convention for "I'm not using this
part").

note1: notice the "*" in the def line, it makes the function accept a
variable number of arguments, so you can call it as collect_ext('.py')
but also as collect_ext('.py', '.pyw', '.pyo'). Inside the function,
what you've called it with is a list (or a tuple, I forget), which
means I can use the _in_ operator in the if test.

note2: I use os.path.join() to attach the directory name to the
filename before appending it to the result. It seems that might be
useful ;-)

hth,
-- bjorn

Aug 8 '06 #20

P: n/a
Here's my code:

def getFileList():
import os
imageList = []
for dirpath, dirnames, filenames in os.walk(os.getcwd()):
for filename in filenames:
for dirname in dirnames:
if not dirname.startswith('.'):
if filename.lower().endswith('.jpg') and not
filename.startswith('.'):
imageList.append(os.path.join(dirpath, filename))
return imageList

I've adapted it around all the much appreciated suggestions. However,
I'm running into two very peculiar logical errors. First, I'm getting
repeated entries. That's no good. One image, one entry in the list.
The other is that if I run the script from my Desktop folder, it won't
find any files, and I make sure to have lots of jpegs in the Desktop
folder for the test. Can anyone figure this out?

ja*******@gmail.com wrote:
I'm new at Python and I need a little advice. Part of the script I'm
trying to write needs to be aware of all the files of a certain
extension in the script's path and all sub-directories. Can someone
set me on the right path to what modules and calls to use to do that?
You'd think that it would be a fairly simple proposition, but I can't
find examples anywhere. Thanks.
Aug 9 '06 #21

P: n/a
Something's really not reliable in my logic. I say this because if I
change the extension to .png then a file in a hidden directory (one the
starts with '.') shows up! The most frustrating part is that there are
..jpg files in the very same directory that don't show up when it
searches for jpegs.

I tried os.walk('.') and it works, so I'll be using that instead.

ja*******@gmail.com wrote:
Here's my code:

def getFileList():
import os
imageList = []
for dirpath, dirnames, filenames in os.walk(os.getcwd()):
for filename in filenames:
for dirname in dirnames:
if not dirname.startswith('.'):
if filename.lower().endswith('.jpg') and not
filename.startswith('.'):
imageList.append(os.path.join(dirpath, filename))
return imageList

I've adapted it around all the much appreciated suggestions. However,
I'm running into two very peculiar logical errors. First, I'm getting
repeated entries. That's no good. One image, one entry in the list.
The other is that if I run the script from my Desktop folder, it won't
find any files, and I make sure to have lots of jpegs in the Desktop
folder for the test. Can anyone figure this out?

ja*******@gmail.com wrote:
I'm new at Python and I need a little advice. Part of the script I'm
trying to write needs to be aware of all the files of a certain
extension in the script's path and all sub-directories. Can someone
set me on the right path to what modules and calls to use to do that?
You'd think that it would be a fairly simple proposition, but I can't
find examples anywhere. Thanks.
Aug 9 '06 #22

P: n/a
At Tuesday 8/8/2006 21:11, ja*******@gmail.com wrote:

>Here's my code:

def getFileList():
import os
imageList = []
for dirpath, dirnames, filenames in os.walk(os.getcwd()):
for filename in filenames:
for dirname in dirnames:
if not dirname.startswith('.'):
if
filename.lower().endswith('.jpg') and not
filename.startswith('.'):

imageList.append(os.path.join(dirpath, filename))
return imageList

I've adapted it around all the much appreciated suggestions. However,
I'm running into two very peculiar logical errors. First, I'm getting
repeated entries. That's no good. One image, one entry in the list.
That's because of the double iteration. dirnames and filenames are
two distinct, complementary, lists. (If a directory entry is a
directory it goes into dirnames; if it's a file it goes into
filenames). So you have to process them one after another.
>def getFileList():
import os
imageList = []
for dirpath, dirnames, filenames in os.walk(os.getcwd()):
for filename in filenames:
if filename.lower().endswith('.jpg') and
not filename.startswith('.'):

imageList.append(os.path.join(dirpath, filename))
for i in reversed(range(len(dirnames))):
if dirnames[i].startswith('.'): del dirnames[i]
return imageList
reversed() because you need to modify dirnames in-place, so it's
better to process the list backwards.

Gabriel Genellina
Softlab SRL

__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Aug 9 '06 #23

P: n/a
I've narrowed down the problem. All the problems start when I try to
eliminate the hidden files and directories. Is there a better way to
do this?
ja*******@gmail.com wrote:
I'm new at Python and I need a little advice. Part of the script I'm
trying to write needs to be aware of all the files of a certain
extension in the script's path and all sub-directories. Can someone
set me on the right path to what modules and calls to use to do that?
You'd think that it would be a fairly simple proposition, but I can't
find examples anywhere. Thanks.
Aug 9 '06 #24

P: n/a
That worked perfectly. Thank you. That was exactly what I was looking
for. However, can you explain to me what the following code actually
does?

reversed(range(len(dirnames)))
Gabriel Genellina wrote:
At Tuesday 8/8/2006 21:11, ja*******@gmail.com wrote:

Here's my code:

def getFileList():
import os
imageList = []
for dirpath, dirnames, filenames in os.walk(os.getcwd()):
for filename in filenames:
for dirname in dirnames:
if not dirname.startswith('.'):
if
filename.lower().endswith('.jpg') and not
filename.startswith('.'):

imageList.append(os.path.join(dirpath, filename))
return imageList

I've adapted it around all the much appreciated suggestions. However,
I'm running into two very peculiar logical errors. First, I'm getting
repeated entries. That's no good. One image, one entry in the list.

That's because of the double iteration. dirnames and filenames are
two distinct, complementary, lists. (If a directory entry is a
directory it goes into dirnames; if it's a file it goes into
filenames). So you have to process them one after another.
def getFileList():
import os
imageList = []
for dirpath, dirnames, filenames in os.walk(os.getcwd()):
for filename in filenames:
if filename.lower().endswith('.jpg') and
not filename.startswith('.'):

imageList.append(os.path.join(dirpath, filename))
for i in reversed(range(len(dirnames))):
if dirnames[i].startswith('.'): del dirnames[i]
return imageList

reversed() because you need to modify dirnames in-place, so it's
better to process the list backwards.

Gabriel Genellina
Softlab SRL

__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas
Aug 9 '06 #25

P: n/a
ja*******@gmail.com wrote:
I've narrowed down the problem. All the problems start when I try to
eliminate the hidden files and directories. Is there a better way to
do this?
Well you almost have it, but your problem is that you are trying to do
too many things in one function. (I bet I am starting to sound like a
broken record :-)) The four distinct things you are doing are:

* getting a list of all files in a tree
* combining a files directory with its name to give the full path
* ignoring hidden directories
* matching files based on their extension

If you split up each of those things into their own function you will
end up with smaller easier to test pieces, and separate, reusable
functions.

The core function would be basically what you already have:

def get_files(directory, include_hidden=False):
"""Return an expanded list of files for a directory tree
optionally not ignoring hidden directories"""
for path, dirs, files in os.walk(directory):
for fn in files:
full = os.path.join(path, fn)
yield full

if not include_hidden:
remove_hidden(dirs)

and remove_hidden is a short, but tricky function since the directory
list needs to be edited in place:

def remove_hidden(dirlist):
"""For a list containing directory names, remove
any that start with a dot"""

dirlist[:] = [d for d in dirlist if not d.startswith('.')]

at this point, you can play with get_files on it's own, and test
whether or not the include_hidden parameter works as expected.

For the final step, I'd use an approach that pulls out the extension
itself, and checks to see if it is in a list(or better, a set) of
allowed filenames. globbing (*.foo) works as well, but if you are only
ever matching on the extension, I believe this will work better.

def get_files_by_ext(directory, ext_list, include_hidden=False):
"""Return an expanded list of files for a directory tree
where the file ends with one of the extensions in ext_list"""
ext_list = set(ext_list)

for fn in get_files(directory, include_hidden):
_, ext = os.path.splitext(fn)
ext=ext[1:] #remove dot
if ext.lower() in ext_list:
yield fn

notice at this point we still haven't said anything about images! The
task of finding files by extension is pretty generic, so it shouldn't
be concerned about the actual extensions.

once that works, you can simply do

def get_images(directory, include_hidden=False):
image_exts = ('jpg','jpeg','gif','png','bmp')
return get_files_by_ext(directory, image_exts, include_hidden)

Hope this helps :-)

--
- Justin

Aug 9 '06 #26

P: n/a
I do appreciate the advice, but I've got a 12 line function that does
all of that. And it works! I just wish I understood a particular line
of it.

def getFileList(*extensions):
import os
imageList = []
for dirpath, dirnames, files in os.walk('.'):
for filename in files:
name, ext = os.path.splitext(filename)
if ext.lower() in extensions and not filename.startswith('.'):
imageList.append(os.path.join(dirpath, filename))
for dirname in reversed(range(len(dirnames))):
if dirnames[dirname].startswith('.'):
del dirnames[dirname]

return imageList

print getFileList('.jpg', '.gif', '.png')

The line I don't understand is:
reversed(range(len(dirnames)))
Justin Azoff wrote:
ja*******@gmail.com wrote:
I've narrowed down the problem. All the problems start when I try to
eliminate the hidden files and directories. Is there a better way to
do this?

Well you almost have it, but your problem is that you are trying to do
too many things in one function. (I bet I am starting to sound like a
broken record :-)) The four distinct things you are doing are:

* getting a list of all files in a tree
* combining a files directory with its name to give the full path
* ignoring hidden directories
* matching files based on their extension

If you split up each of those things into their own function you will
end up with smaller easier to test pieces, and separate, reusable
functions.

The core function would be basically what you already have:

def get_files(directory, include_hidden=False):
"""Return an expanded list of files for a directory tree
optionally not ignoring hidden directories"""
for path, dirs, files in os.walk(directory):
for fn in files:
full = os.path.join(path, fn)
yield full

if not include_hidden:
remove_hidden(dirs)

and remove_hidden is a short, but tricky function since the directory
list needs to be edited in place:

def remove_hidden(dirlist):
"""For a list containing directory names, remove
any that start with a dot"""

dirlist[:] = [d for d in dirlist if not d.startswith('.')]

at this point, you can play with get_files on it's own, and test
whether or not the include_hidden parameter works as expected.

For the final step, I'd use an approach that pulls out the extension
itself, and checks to see if it is in a list(or better, a set) of
allowed filenames. globbing (*.foo) works as well, but if you are only
ever matching on the extension, I believe this will work better.

def get_files_by_ext(directory, ext_list, include_hidden=False):
"""Return an expanded list of files for a directory tree
where the file ends with one of the extensions in ext_list"""
ext_list = set(ext_list)

for fn in get_files(directory, include_hidden):
_, ext = os.path.splitext(fn)
ext=ext[1:] #remove dot
if ext.lower() in ext_list:
yield fn

notice at this point we still haven't said anything about images! The
task of finding files by extension is pretty generic, so it shouldn't
be concerned about the actual extensions.

once that works, you can simply do

def get_images(directory, include_hidden=False):
image_exts = ('jpg','jpeg','gif','png','bmp')
return get_files_by_ext(directory, image_exts, include_hidden)

Hope this helps :-)

--
- Justin
Aug 9 '06 #27

P: n/a
ja*******@gmail.com wrote:
I do appreciate the advice, but I've got a 12 line function that does
all of that. And it works! I just wish I understood a particular line
of it.
You miss the point. The functions I posted, up until get_files_by_ext
which is the equivalent of your getFileList, total 17 actual lines.
The 5 extra lines give 3 extra features. Maybe in a while when you
need to do a similar file search you will realize why my way is better.

[snip]
The line I don't understand is:
reversed(range(len(dirnames)))
This is why I wrote and documented a separate remove_hidden function,
it can be tricky. If you broke it up into multiple lines, and added
print statements it would be clear what it does.

l = len(dirnames) # l is the number of elements in dirnames, e.g. 6
r = range(l) # r contains the numbers 0,1,2,3,4,5
rv = reversed(r) # rv contains the numbers 5,4,3,2,1,0

The problem arises from how to remove elements in a list as you are
going through it. If you delete element 0, element 1 then becomes
element 0, and funny things happen. That particular solution is
relatively simple, it just deletes elements from the end instead. That
complicated expression arises because python doesn't have "normal" for
loops. The version of remove_hidden I wrote is simpler, but relies on
the even more obscure lst[:] construct for re-assigning a list. Both
of them accomplish the same thing though, so if you wanted, you should
be able to replace those 3 lines with just

dirnames[:] = [d for d in dirnames if not d.startswith('.')]
--
- Justin

Aug 9 '06 #28

P: n/a
ja*******@gmail.com wrote:
I do appreciate the advice, but I've got a 12 line function that does
all of that. And it works! I just wish I understood a particular line
of it.

def getFileList(*extensions):
import os
imageList = []
for dirpath, dirnames, files in os.walk('.'):
for filename in files:
name, ext = os.path.splitext(filename)
if ext.lower() in extensions and not filename.startswith('.'):
imageList.append(os.path.join(dirpath, filename))
for dirname in reversed(range(len(dirnames))):
if dirnames[dirname].startswith('.'):
del dirnames[dirname]

return imageList

print getFileList('.jpg', '.gif', '.png')

The line I don't understand is:
reversed(range(len(dirnames)))
For a start, change "dirname" to "dirindex" (without changing
"dirnames"!) in that line and the next two lines -- this may help your
understanding.

The purpose of that loop is to eliminate from dirnames any entries
which start with ".". This needs to be done in-situ -- concocting a new
list and binding the name "dirnames" to it won't work.
The safest understandable way to delete entries from a list while
iterating over it is to do it backwards.

Doing it forwards doesn't always work; example:

#>>dirnames = ['foo', 'bar', 'zot']
#>>for x in range(len(dirnames)):
.... if dirnames[x] == 'bar':
.... del dirnames[x]
....
Traceback (most recent call last):
File "<stdin>", line 2, in ?
IndexError: list index out of range

HTH,
John

Aug 9 '06 #29

P: n/a
I'm sorry. I didn't mean to offend you. I never thought your way was
inferior.
Justin Azoff wrote:
ja*******@gmail.com wrote:
I do appreciate the advice, but I've got a 12 line function that does
all of that. And it works! I just wish I understood a particular line
of it.

You miss the point. The functions I posted, up until get_files_by_ext
which is the equivalent of your getFileList, total 17 actual lines.
The 5 extra lines give 3 extra features. Maybe in a while when you
need to do a similar file search you will realize why my way is better.

[snip]
The line I don't understand is:
reversed(range(len(dirnames)))

This is why I wrote and documented a separate remove_hidden function,
it can be tricky. If you broke it up into multiple lines, and added
print statements it would be clear what it does.

l = len(dirnames) # l is the number of elements in dirnames, e.g. 6
r = range(l) # r contains the numbers 0,1,2,3,4,5
rv = reversed(r) # rv contains the numbers 5,4,3,2,1,0

The problem arises from how to remove elements in a list as you are
going through it. If you delete element 0, element 1 then becomes
element 0, and funny things happen. That particular solution is
relatively simple, it just deletes elements from the end instead. That
complicated expression arises because python doesn't have "normal" for
loops. The version of remove_hidden I wrote is simpler, but relies on
the even more obscure lst[:] construct for re-assigning a list. Both
of them accomplish the same thing though, so if you wanted, you should
be able to replace those 3 lines with just

dirnames[:] = [d for d in dirnames if not d.startswith('.')]
--
- Justin
Aug 9 '06 #30

This discussion thread is closed

Replies have been disabled for this discussion.