Replacing text for all files in a directory

Kemp Randy-W18971 Randy.L.Kemp at
Wed Aug 8 14:43:14 CEST 2001

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

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

Kemp Randy-W18971 <Randy.L.Kemp at> 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
> replace all occurrences of the text "Have a good day" to "jump off a
> 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 =

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

This is UNTESTED code. Use at your own risk.

  Harald Kirsch

Harald Kirsch   | kirschh at | "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