newb question: file searching
hiaips
rosedb0 at gmail.com
Tue Aug 8 17:10:33 EDT 2006
jaysherby at 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
More information about the Python-list
mailing list