os.walk trouble

T

The Prophet

As my first Python script, I am trying to make a program that recurses
a directory searching for files whose names match a pattern. I have a
basic idea of what the regexp would look like (and I can get more
information about that), but I am stuck with incorrect understanding of
os.walk. I've tried:

root, dirs, files = os.walk(dirname)

but it fails for some reason. I have seen this done before in the
tutorial (I think it's called sequence unpacking). What is the proper
way to do this?

Thanks in advance.
 
T

Tim Chase

but I am stuck with incorrect understanding of
os.walk. I've tried:

root, dirs, files = os.walk(dirname)

os.walk returns an iteratable sequence of those tuples. Thus,
you want to have

for filepath, dirs, files in os.walk(dirname):
#you're looking at the "dirs" and "files" in filepath
print "Currently in %s" % filepath
print "\t[Directories in %s]" % filepath
print "\n\t".join(dirs)
print "\t[Files in %s]" % filepath
print "\n\t".join(files)
print "=" * 50

HTH,

-tkc
 
B

BartlebyScrivener

Neat. And looks better, at least on my machine, if you had a tab or two
and an extra \n after the dirs.

rick

for filepath, dirs, files in os.walk(root):
#you're looking at the "dirs" and "files" in filepath
print "Currently in %s" % filepath
print "\t[Directories in %s]" % filepath
print '\t' + "\n\t".join(dirs) + '\n'
print "\t[Files in %s]" % filepath
print '\t' + "\n\t".join(files)
print "=" * 50
 
B

BartlebyScrivener

root, dirs, files = os.walk(dirname)

If you want to do it this way, you need to stop it after the first one:

root, dirs, files = os.walk(dirname).next()
print root
print dirs
print files

see this thread

http://tinyurl.com/rmyo4
 
B

BartlebyScrivener

As my first Python script, I am trying to make a program that recurses
a directory searching for files whose names match a pattern. I have a
basic idea of what the regexp would look like

You probably don't need regexp for this, just use the fnmatch module

http://docs.python.org/lib/module-fnmatch.html

There's a great recipe in the Python Cookbook 2ed for just what you're
trying to do. In fact, I believe there's a recipe in there for just
about anything anybody (at the beginner or intermediate level) wants to
do with Python.

The recipe, with some other unrelated problems:

http://tinyurl.com/nvmzg

Amazon Python Cookbook link:

http://www.amazon.com/exec/obidos/asin/0596007973/inscape-20

good luck

rick
 

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
473,780
Messages
2,569,610
Members
45,255
Latest member
TopCryptoTwitterChannels

Latest Threads

Top