Replace and inserting strings within .txt files with the use of regex

Νίκος nikos.the.gr33k at gmail.com
Sun Aug 8 05:21:56 EDT 2010


Script so far:

#!/usr/bin/python

import cgitb; cgitb.enable()
import cgi, re, os

print ( "Content-type: text/html; charset=UTF-8 \n" )


id = 0  # unique page_id

for currdir, files, dirs in os.walk('data'):

    for f in files:

        if f.endswith('php'):

            # get abs path to filename
            src_f = join(currdir,f)

            # open php src file
            f = open(src_f, 'r')
            src_data = f.read()         # read contents of PHP file
            f.close()
            print 'reading from %s' % src_f

            # replace tags
            src_data = src_data.replace('<%', '')
            src_data = src_data.replace('%>', '')
            print 'replacing php tags'

            # add ID
            src_data = ( '<!-- %d -->' % id ) + src_data
            id += 1
            print 'adding unique page_id'

            # create new file with .html extension
            src_file = src_file.replace('.php', '.html')

            # open newly created html file for insertid data
            dest_f = open(src_f, 'w')
            dest_f.write(src_data)      # write contents
            dest_f.close()
            print 'writing to %s' % dest_f

Please help me adjust it, if need extra modification for more php tags
replacing.



More information about the Python-list mailing list