[Tutor] Replacing the string in a file

vanam raghavendra.gv.vanam at gmail.com
Fri Jan 22 07:44:05 CET 2010


Hi all,

I have been trying to write a script where in it has to replace a
particular string in a file and write back to the file without intact
of the contents

I have tried below mentioned steps, but of no avail:

1. Created a file by name data.txt and included some text (For
instance,

************************************************************************
Then, I started searching for a good book on Python. I couldn't find
any! I did find some O'Reilly books
but they were either too expensive or were more like a reference
manual than a guide. So, I settled for
the documentation that came with Python. However, it was too brief and
small. It did give a good idea
about Python but was not complete. I managed with it since I had
previous programming experience, but
it was unsuitable for newbies.
************************************************************************

2.Read the file contents (For this opened the file in read mode -- log
= open('data.txt','r')

3.Iterated through the text using for loop for reading the contents in
the file -- for x in log:

4.Replaced the word  Python with PYTHON as indicated --- x  =
x.replace('Python','PYTHON')

6.printed the full contents -- It had printed the full contents by
replacing the word Python to PYTHON

Python string did not get changed to PYTHON for the reasons that i did
not open the file in write mode and written the string

[Query]: How to write Python string to PYTHON to that file without
intact of the full contents

I was successful in routing the contents (with changed string to
PYTHON) to a different file.

And i am aware that opening the file in write mode will wipe out the
previous contents.

I have tried appending the content which it does but that is not my goal.


7. Closed the files outside for loop -- log.close()
-- 
Raghavendra  Vanam


More information about the Tutor mailing list