A question

Michael Hudson mwh21 at cam.ac.uk
Sun Oct 17 16:04:33 EDT 1999


wware-nospam at world.std.com (Will Ware) writes:

> Kristian Nylund (krnylund at io.yok.utu.fi) wrote:
> : Could someone tell me an easy way to do  
> : something like "for i in `ls *.txt`..." 
> : in python?
> 
> Other folks have mentioned glob.glob(), which will work fine for
> things like "*.txt". If you want something more flexible, for
> instance all the *.c and *.h files that mention printf,
> you'd want to iterate on the output of something like
> 
> 	find . -name '*.[ch]' -exec grep -l printf {} \;
> 
> and if you wanted to do something like that in Python, you'd want
> to know about commands.getoutput(). Specifically, you'd want to
> write something like this:
> 
> 	import commands
> 
> 	for file in commands.getoutput(
> 		"find . -name '*.[ch]' -exec grep -l printf {} \;"):
> 	    process(file)

I promise you that doesn't do what you expect: (I changed the command
line; you'll see why ;-)


for i in commands.getoutput(
          "find ~/src/haskell/ -name '*.lhs' -exec grep -l printf {} \;"):
    print i,":",

yields:

/ : h : o : m : e : / : m : w : h : 2 : 1 : / : s : r : c : / : h : a : s : k : e : l : l : / : H : u : g : s : 9 : 8 : / : l : i : b : / : e : x : t : s : / : D : y : n : a : m : i : c : . : l : h : s :

Oops. Thought's there, just need string.split(blah,"\n").

> So commands.getoutput() is good to know about if you need a little
> more flexibility than glob.glob().

Indeed.

hth,
Michael




More information about the Python-list mailing list