Walk thru each subdirectory from a top directory
Jeff McNeil
jeff at jmcneil.net
Mon Feb 26 16:52:45 EST 2007
Isn't this something that os.walk would be good for?
import os
for t in os.walk(base_dir):
for f in t[2]:
print "/".join((t[0], f))
Jeff
On Feb 26, 2007, at 4:42 PM, Sick Monkey wrote:
> I had a do something similar. I had to get a program to traverse
> through a directory and delete all files with a specific file
> extension. (The program below will delete files, so I do not
> recommend you running it without paying close attention to it.)
>
> This program will start at a given directory and will traverse thru
> the subdirectories by using "listdir".
> +++++++++++++++++++++++++++++++++++
> #!/usr/bin/python -u
>
> import sys, time
> from os import listdir, unlink
> from os.path import isdir, isfile, islink, join, getmtime
> deldir = "C:\some\Dir"
> delFileType = ".txt"
> # -------------------------------------
> def del_entry(_name):
> try:
> if isdir(_name):
> print "This is a directory, do nothing."
> else:
> #print "now"
> unlink(_name) # or remove(_name)
> sys.stdout.write("Delete FILE %s\n" % (_name))
> except IOError:
> sys.stderr.write("Cannot delete %s\n" % (_name))
> # -------------------------------------
> def list_dir(_dir,_action):
> if not isdir(_dir):
> print "%s is not a directory" % (_dir)
> return
>
> for file in listdir(_dir):
> path = join(_dir, file)
> if isdir(path):
> list_dir(path, _action)
> else:
> if path.rfind(delFileType) != -1:
> #print path
> _action(path)
> # -------------------------------------
> # Run it
> list_dir(deldir, del_entry)
>
> On 26 Feb 2007 13:28:20 -0800, silverburgh.meryl at gmail.com
> <silverburgh.meryl at gmail.com> wrote:
>
> i am trying to use python to walk thru each subdirectory from a top
> directory. Here is my script:
>
> savedPagesDirectory = "/home/meryl/saved_pages/data"
>
> dir=open(savedPagesDirectory, 'r')
>
> for file in dir:
> if (isdir(file)):
> # get the full path of the file
> fileName = savedPagesDirectory + file + 'index.html'
> print fileName
>
> $ ./scripts/regressionTest.py
> Traceback (most recent call last):
> File "./scripts/regressionTest.py", line 12, in ?
> dir=open(savedPagesDirectory, 'r')
> IOError: [Errno 21] Is a directory
>
> But I get the above error:
>
> Can you please tell me what did I do wrong?
>
> Thank you.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
> --
> http://mail.python.org/mailman/listinfo/python-list
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20070226/b71ca089/attachment.html>
More information about the Python-list
mailing list