15

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"
Martin
  • 10,294
  • 11
  • 63
  • 83

2 Answers2

31

Try this:

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

And then continue processing.

user225312
  • 126,773
  • 69
  • 172
  • 181
8

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()
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 1
    may i ask? i know that python follows the rule 'easier ask forgiveness than permisison' but in this case isn't better a simple if '.svn':#etc like in the example above? i find that syntax ugly; can you give me an advice? – Ant Nov 25 '10 at 14:00
  • @Ant: That's just how I roll. – Ignacio Vazquez-Abrams Nov 25 '10 at 17:10