Walk thru each subdirectory from a top directory

Scott David Daniels scott.daniels at acm.org
Tue Feb 27 23:31:43 EST 2007


Adam wrote:
> 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: ....
> 
> 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)
       ^^^ Mistake here, don't change directories during os.walk ^^^
>             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

     def produce_all_files(base):
         for root, dirs, files in os.walk(base):
             for r in files:
                 yield os.path.join(root, r)
             ### possibly also (but I'd only go for files)
             #for r in dirs:
             #    yield os.path.join(root, r)

     def findallfiles(base):
         return list(produce_all_files(base))

-- 
--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list