newb question: file searching

J

jaysherby

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.
 
G

godavemon

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.
 
G

godavemon

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.
 
H

hiaips

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
 
J

jaysherby

Mike said:

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?
 
H

hiaips

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
 
J

jaysherby

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.

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
 
J

Jason

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 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.
 
H

hiaips

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
 
H

hiaips

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
 
J

jaysherby

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.
 
S

Simon Forman

hiaips said:
(e-mail address removed) 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
 
S

Steve M

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)]
 
J

jaysherby

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
 
G

Gabriel Genellina

At said:
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
 
J

John Machin

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
 
S

Steve M

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
 
I

infidel

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.
 
T

thebjorn

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
 

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

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,276
Latest member
Sawatmakal

Latest Threads

Top