Replacing text for all files in a directory

Kemp Randy-W18971 Randy.L.Kemp at motorola.com
Wed Aug 8 08:43:14 EDT 2001


Thanks!.  I will try this on my test machine with test files first.

-----Original Message-----
From: Harald Kirsch [mailto:kirschh at lionbioscience.com]
Sent: Wednesday, August 08, 2001 2:18 AM
To: python-list at python.org
Subject: Re: Replacing text for all files in a directory


Kemp Randy-W18971 <Randy.L.Kemp at motorola.com> writes:

> 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? 
> 

Everyone, (even me) seems to be sure that this calls for something
sh/sed/awk like. Nevertheless, I'll try a Python one.

import glob
import re

## loop over all file names in the current directory
for fname in glob.glob("*"):
  ## slurp in the whole file
  fin = open(fname)
  text = fin.read()
  fin.close()

  ## do the replacement in memory  
  s =  re.sub("your pattern here", "the replacement text", text)

  ## dump it out
  fout = open(fname, "w")      # WATCH OUT, THIS DELETES THE OLD FILE
  fout.write(s)
  fout.close()

This is UNTESTED code. Use at your own risk.

  Harald Kirsch

-- 
----------------+------------------------------------------------------
Harald Kirsch   | kirschh at lionbioscience.com | "How old is the epsilon?"
LION bioscience | +49 6221 4038 172          |        -- Paul Erdös
       *** Please do not send me copies of your posts. ***




More information about the Python-list mailing list