deboleena
deboleena

Reputation: 1

searching and processing particular directory and files in python

In my present directory I have the following files: project1, project5, junk, temp and personal

I would like to walk through the sub directories at this level only. For directories other than junk, temp and personal I would like to open and process a particular file present in them say called project.c

for dirs in os.walk('.').next()[1] :  
      if dirs !='junk' or dirs!='temp' or dirs != 'personal':  
        print dirs  
        print "relevant\n"
        # file = open(project//project.c) # process relevant files 

How do I go about doing that ?

Upvotes: 0

Views: 494

Answers (3)

Nathan Ernst
Nathan Ernst

Reputation: 4590

From the python documentation here, dirnames can be modified to affect the traversal:

When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again. Modifying dirnames when topdown is False is ineffective, because in bottom-up mode the directories in dirnames are generated before dirpath itself is generated.

So, you can do something like:

def clean(dirs):
    to_ignore = ("tmp", "junk", "personal")
    for d in to_ignore:
        if d in dirs:
            dirs.remove(d)

for dirpath, dirnames, filenames in os.walk('.'):
    clean(dirnames)
    # process relevant files

Upvotes: 0

Mark
Mark

Reputation: 195

And here's another, somewhat similar way

ignored=set(('junk','temp','personal'))
projectfiles=set(('project.c','Makefile.in'))

for direntry in os.listdir('.') :
   if not direntry in ignored :
      filename=os.path.join(os.path.dirname('.'),direntry)
      if os.path.isdir(filename) :
         for projectfile in projectfiles :
            projectfilepath=os.path.join(filename,projectfile)
            if os.path.exists(projectfilepath) :
            fd=open(projectfilepath)
            # Do whatever processing is needed
            fd.close()

Upvotes: 0

AlG
AlG

Reputation: 15157

Here's one way:

import os
import glob

ignoreDirs = ['junk', 'temp', 'personal']

for x in glob.glob('*'):
    if (os.path.isdir(x) == False):
        continue

    if (x in ignoreDirs):
        continue

    # ... do processing work here ...

Upvotes: 1

Related Questions