//
you're reading...
Python, Source Code, Technology

Python – Find and Replace

Here is a simple python script that would help in finding and replacing text in a file using python

import os
import sys

nargs = len(sys.argv)

if nargs < 5:
    print "usage %s Search_text Replace_text infile outfile"% os.path.basename(sys.argv[0])
else:
    stext = sys.argv[1]
    rtext = sys.argv[2]
    input_file = open(sys.argv[3])
    output_file = open(sys.argv[4],"w")
    for s in input_file:
        output_file.write(s.replace(stext,rtext))
    output_file.close();
    input_file.close();
Advertisements

Discussion

One thought on “Python – Find and Replace

  1. This is awesome, simple too awesome not to bookmark 🙂
    I have just bookmarked it in case I later have a need to replace text in Python.

    Thanks for sharing.

    Posted by Sandra Todd | October 11, 2009, 2:05 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: