Replacing text for all files in a directory

Kemp Randy-W18971 Randy.L.Kemp at motorola.com
Tue Aug 7 22:20:24 CEST 2001


Great!  But how can I apply this to all files in a directory, where the
directory contains 20 files, without listing each file individually?

-----Original Message-----
From: William Park [mailto:opengeometry at yahoo.ca]
Sent: Tuesday, August 07, 2001 3:13 PM
To: Kemp Randy-W18971
Cc: python-list at python.org
Subject: Re: Replacing text for all files in a directory


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