Wednesday, May 31, 2017

Change filenames and replace string within files

Change filenames and replace string within files.

import os
import fnmatch
import shutil
import re

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, 'pattern_*.v'):
        p = re.compile('pattern_')
        dest = 'new_dir/' + p.sub('new_pattern_',file)
        print 'new_dir/' + dest
        shutil.copyfile(file, dest)

        with open(dest, 'r') as file:
            filedata = file.read()
        filedata = filedata.replace('pattern_', 'new_pattern_')

        flag = True
        newfile = ""
        for line in filedata.splitlines():
            if re.search(r"^.ifdef", line):
                flag = True
                continue
            elif re.search(r"^.else", line):
                flag = False
            elif re.search(r"^.endif", line):
                flag = True
                continue
            if flag :
                newfile = newfile + line + '\n'

        with open(dest, 'w') as file:
            file.write(newfile)
            #file.write(filedata)