27 de fevereiro de 2008

Achar e mudar

Recentemente surgiu a necessidade de encontrar e alterar determinadas expressões dentro dos arquivos.py de todos os subdiretórios de uma pasta. Segue o código.

#!/usr/bin/env python

# changetool.py


import os, os.path

def run():
 print "At any moment type '@quit@' to quit."
 path = raw_input("Dir path ('enter' for local): ")
 if path.strip() == '@quit@':
     return
 find = raw_input("Find: ")
 if find.strip() == '@quit@':
     return
 replace_for = raw_input("Replace for: ")
 if replace_for.strip() == '@quit@':
     return
 if not path:
     path = "."
 tree = [item[0] for item in os.walk(path)]
 py_files = list_py_files(tree)
 replace(py_files, find, replace_for)
 print ""
 another = raw_input("Replacements done. "
                     "Do you want to do another one (y/n)? ")
 if another.lower().strip() == 'y':
     run()

def list_py_files(dirs):
 files = []
 for path in dirs:
     files += [os.path.join(path, i) for i in os.listdir(path)
               if i.endswith(".py") or i.endswith(".pyw")]
               #or i.endswith(".glade") or i.endswith(".st")]
 return files

def replace(files, find, replace_for):
 print ""
 print "---------------------------------"
 for file in files:
     lines = open(file).readlines()
     new_lines = []
     for index, line in enumerate(lines):
         if find in line:
             print "File:", file
             print "Line number:", (index+1)
             print "Found:", line.strip()
             line = line.replace(find, replace_for)
             print "Replaced for:", line.strip()
             print "---------------------------------"
         new_lines.append(line)
     if lines != new_lines:
         open(file, "w").write("".join(new_lines))

run()


>>> """ Se você tem alguma contribuição, melhoramento ou sugestão para fazer, fique à vontade. """

Nenhum comentário: