Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

os.walk exclude .svn folders

Tags:

python

I got a script that I want to use to change a repeated string throughout a project folder structure. Once changed then I can check this into SVN. However when I run my script it goes into the .svn folders which I want it to ingore. How can I achieve this? Code below, thanks.

import os
import sys

replacement = "newString"
toReplace = "oldString"
rootdir = "pathToProject"


for root, subFolders, files in os.walk(rootdir):
  print subFolders
  if not ".svn" in subFolders:
    for file in files:
      fileParts = file.split('.')
      if len(fileParts) > 1:
        if not fileParts[len(fileParts)-1] in ["dll", "suo"]:
          fpath = os.path.join(root, file)
          with open(fpath) as f:
            s = f.read()
          s = s.replace(toReplace, replacement)
          with open(fpath, "w") as f:
            f.write(s)

print "DONE"
like image 658
Martin Avatar asked Nov 25 '10 10:11

Martin


2 Answers

Try this:

for root, subFolders, files in os.walk(rootdir):
    if '.svn' in subFolders:
      subFolders.remove('.svn')

And then continue processing.

like image 98
user225312 Avatar answered Sep 22 '22 02:09

user225312


Err... what?

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.

for root, subFolders, files in os.walk(rootdir):
  try:
    subFolders.remove('.svn')
  except ValueError:
    pass
  dosomestuff()
like image 8
Ignacio Vazquez-Abrams Avatar answered Sep 18 '22 02:09

Ignacio Vazquez-Abrams