1

Im a noob to python and I am trying to complete this simple task. I want to access multiple directories one by one that are all located inside one directory. I do not have the names of the multiple directories. I need to enter into the directory, combine some files, move back out of that directory, then into the next directory, combine some files, move back out of it, and so on........ I need to make sure I dont access the same directory more than once.

I looked around and tried various commands and nothing yet.

user2353003
  • 522
  • 1
  • 7
  • 18

2 Answers2

2

try using something like the following piece of code.:

import os, fnmatch

def find_files(directory, pattern):
    for root, dirs, files in os.walk(directory):
        for basename in files:
            if fnmatch.fnmatch(basename, pattern):
                filename = os.path.join(root, basename)

                yield filename

use it something like this:

for filename in find_files('/home/', '*.html')
    # do something
PepperoniPizza
  • 8,842
  • 9
  • 58
  • 100
0

Sometimes I find glob to be useful:

from glob import glob
import os

nodes = glob('/tmp/*/*')

for node in nodes:
    try:
        print 'now in directory {}'.format(os.path.dirname(node))
        with open(node, 'r') as f:
            # Do something with f...
            print len(f.read())
    except IOError:  # Because node may be a directory, which we cannot 'open'
        continue
Captain Midday
  • 659
  • 8
  • 18