вторник, 30 октября 2007 г.

Питон в примерах. 1

Простой скрипт, который в заданной папке ищет все файлы в которых есть строка1 и меняет ей на строку2.

import os, sys, string
'''
find findStr and replace by repStr in all *.html files of selected directory
usage:
python findandreplace.py /home/user/path findStr repString
'''

findStr = ''
repStr = ''
fileCounter = 0

def readFile(path):
fh = open(path, "r")
buf = fh.read()
fh.close()
return buf

def writeFile(path, str):
fh = open(path, "w")
fh.write(str)
fh.close()


def replaceStringInFile(findStr,repStr,filePath):
"replaces all findStr by repStr in file filePath"

global fileCounter

buf = readFile(filePath)
bunew = ''

if buf.find(findStr) != -1:
bufnew = buf.replace(findStr,repStr)

print filePath
fileCounter += 1

os.remove(filePath)
writeFile(filePath, str(bufnew))


def walk_func(dummy, dirs, files):
global findStr, repStr
for file in files:
if str(dirs).find('.svn') == -1 and os.path.isfile(dirs+'/'+file)\
and file.find('.htm') == -1:
replaceStringInFile(findStr,repStr,dirs+'/'+file)


def main():
global findStr, repStr, fileCounter

targetDir = sys.argv[1]
findStr = sys.argv[2]
#findStr = ''
repStr = sys.argv[3]
#repStr = ''

os.path.walk(targetDir, walk_func, 0)
print 'Total: ', fileCounter


if __name__ == "__main__":
main()

Комментариев нет: