Posts Tagged ‘python’

Search and Replace PHP split() with Python

Tuesday, May 4th, 2010

A couple of days ago I upgraded to Ubuntu 10.04 which, in turn, upgraded my PHP version from 5.2 to 5.3. In PHP 5.3 they have completely deprecated the use of the split() function in favour of explode(). I did a quick search in my /work directory and it turns out that I have 832 files that are affected by this. All of them need to have split() replaced with explode() or the websites will throw errors every time they encounter it.

Here’s how I did it using an altered Python script I wrote a couple of years ago:

#!  /usr/bin/python
import os
import re

mydir = "/home/damian/work"

def doReplace(filePath):
	fin = open(filePath, "r")
	s = fin.read()
	fin.flush()
	fin.close()
	p = re.compile('(\s|\(|=)split\(')
	if p.search(s):
		fout = open(filePath, "w")
		s = p.sub(r'\1explode(', s)
		fout.write(s)
		fout.close()

for root, dirs, files in os.walk(mydir):
	for f in files:
		name, ext = os.path.splitext(f)
		if ext == '.php':
			doReplace(root + '/' + f)

(**UPDATE** I’ve switched the search and replace to use regular expressions because I found that ‘split()’ can be prefixed by a number of symbols but not others — i.e. don’t replace ‘preg_split()’)

Search and Replace text in files with Python

Thursday, November 29th, 2007

#!  /usr/bin/python2.5
import os

mydir = "/path/to/directory"
mysearch = "text to find"
myreplace = "Text to replace"

def doReplace(filePath):
    fin = open(filePath, "r")
    s = fin.read()
    fin.flush()
    fin.close()
    fout = open(filePath, "w")
    s = s.replace(mysearch, myreplace)
    fout.write(s)
    fout.close()

for root, dirs, files in os.walk(mydir):
    for f in files:
        name, ext = os.path.splitext(f)
        if ext == '.html':
            doReplace(root + '/' + f)

Explanation: This will find all files ending in .html in the directory specified in mydir along with all matching files in any subfolders and will replace the text specified in mysearch with the text in myreplace. It’s only been tested on Linux but with a bit of tweaking will run on Windows and Mac.