Replacing text for all files in a directory

William Park opengeometry at yahoo.ca
Tue Aug 7 16:12:59 EDT 2001


On Tue, Aug 07, 2001 at 02:25:29PM -0500, Kemp Randy-W18971 wrote:
> Since I don't write Python every day, here is a simple question.  I
> have a directory called test, containing files A, B, ..., Z, and I
> want to replace all occurrences of the text "Have a good day" to "jump
> off a cliff." This is a comic example, but I need to do something
> similar in real life.  How can I do this in Python, running on Unix? 

Yes.  In Python, you would apply
    string.replace(line, 'Have a good day', 'jump off a cliff')
to every line in the file.  If the file is small, then you can slurp the
whole file into memory, and apply 'string.replace()' only once.

But, in my opinion, this calls for shell solution:
    for i in [A-Z]; do
	sed -e "s/Have a good day/jump off a cliff/g" $i > tmp
	mv tmp $i
    done

-- 
William Park, Open Geometry Consulting, <opengeometry at yahoo.ca>
8 CPUs cluster, (Slackware) Linux, Python, LaTeX, Vim, Mutt, Sc.




More information about the Python-list mailing list