Walk thru each subdirectory from a top directory

Adam adamgarstang at googlemail.com
Mon Feb 26 17:43:19 EST 2007


On Feb 26, 9:28 pm, silverburgh.me... 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.

>From Alan Gaulds Tut.

>>> for t in os.walk('Root'):
...    print t
...
('Root', ['D1', 'D2', 'D3'], ['FA.txt', 'FB.txt'])
('Root/D1', ['D1-1'], ['FC.txt'])
('Root/D1/D1-1', [], ['FF.txt'])
('Root/D2', [], ['FD.txt'])
('Root/D3', ['D3-1'], ['FE.txt'])
('Root/D3/D3-1', [], ['target.txt'])
>>>


This bit below is from one of my first programs as I'm currently
learning. It is designed to go form the root down and return the full
paths of everything it finds into a list. (I then check the reults for
files paths that exceed a certain length - but you don't need to know
that.)


    def findallfiles(self, base):
        self.results = []
        for root,dirs,files in os.walk(base):
            os.chdir(root)
            self.scan = glob.glob("*")
            for r in self.scan:
                if root[-1] == "\\":
                    self.results.append(root + r)
                else:
                    self.results.append(root + "\\" + r)
        return self.results





More information about the Python-list mailing list