473,888 Members | 1,573 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Search & Replace

Hello,
I need to search and replace 4 words in a text file.
Below is my attempt at it, but this code appends
a copy of the text file within itself 4 times.
Can someone help me out.
Thanks!

# Search & Replace
file = open("text.txt" , "r")
text = file.read()
file.close()

file = open("text.txt" , "w")
file.write(text .replace("Left_ RefAddr", "FromLeft") )
file.write(text .replace("Left_ NonRefAddr", "ToLeft"))
file.write(text .replace("Right _RefAddr", "FromRight" ))
file.write(text .replace("Right _NonRefAddr", "ToRight"))
file.close()

Oct 26 '06 #1
6 2681
In <11************ **********@f16g 2000cwb.googleg roups.com>, DataSmash
wrote:
I need to search and replace 4 words in a text file.
Below is my attempt at it, but this code appends
a copy of the text file within itself 4 times.
Because you `write()` the whole text four times to the file. Make the 4
replacements first and rebind `text` to the string with the replacements
each time, and *then* write the result *once* to the file.
# Search & Replace
file = open("text.txt" , "r")
text = file.read()
file.close()

file = open("text.txt" , "w")
text = text.replace("L eft_RefAddr", "FromLeft")
text = text.replace("L eft_NonRefAddr" , "ToLeft")
# ...
file.write(text )
file.close()

Ciao,
Marc 'BlackJack' Rintsch
Oct 26 '06 #2
Below is my attempt at it, but this code appends
a copy of the text file within itself 4 times.
Can someone help me out.
[snip]
file = open("text.txt" , "w")
file.write(text .replace("Left_ RefAddr", "FromLeft") )
file.write(text .replace("Left_ NonRefAddr", "ToLeft"))
file.write(text .replace("Right _RefAddr", "FromRight" ))
file.write(text .replace("Right _NonRefAddr", "ToRight"))
file.close()

Well, as you can see, you're writing (write()) the text 4 times.

Looks like you want something like

file.write(text .replace("Left_ RefAddr",
"FromLeft").rep lace("Left_NonR efAddr",
"ToLeft").repla ce("Right_RefAd dr",
"FromRight").re place("Right_No nRefAddr", "ToRight"))
which is about the equiv. of

text = text.replace(.. .1...)
text = text.replace(.. .2...)
text = text.replace(.. .3...)
text = text.replace(.. .4...)
file.write(text )

I would also be remiss if I didn't mention that it's generally
considered bad form to use the variable-name "file", as it
shadows the builtin "file".

There are additional ways if replacements cause problems that
then themselves get replaced, and this is an undesired behavior.
However, it looks like your example doesn't have this problem,
so the matter is moot.

-tkc
Oct 26 '06 #3
DataSmash a écrit :
Hello,
I need to search and replace 4 words in a text file.
Below is my attempt at it, but this code appends
a copy of the text file within itself 4 times.
Can someone help me out.
Thanks!

# Search & Replace
file = open("text.txt" , "r")
NB : avoid using 'file' as an identifier - it shadows the builtin 'file'
type.
text = file.read()
file.close()

file = open("text.txt" , "w")
file.write(text .replace("Left_ RefAddr", "FromLeft") )
file.write(text .replace("Left_ NonRefAddr", "ToLeft"))
file.write(text .replace("Right _RefAddr", "FromRight" ))
file.write(text .replace("Right _NonRefAddr", "ToRight"))
file.close()
See Mark and Tim's answers for your bug. Another (potential) problem
with your code is that it may not work too well for big files. It's ok
if you know that the files content will always be small enough to not
eat all memory. Else, taking a "line by line" approach is the canonical
solution :

def simplesed(src, dest, *replacements):
for line in src:
for target, repl in replacements:
line = line.replace(ta rget, repl)
dest.write(line )

replacements = [
("Left_RefAddr" , "FromLeft") ,
("Left_NonRefAd dr", "ToLeft"),
("Right_RefAddr ", "FromRight" ),
("Right_NonRefA ddr", "ToRight"),
]
src = open("hugetext. txt", "r")
dest = open("some-temp-name.txt", "w")
simplesed(src, dest, *replacements)
src.close()
dest.close()
os.rename("some-temp-name.txt", "hugetext.t xt")

HTH
Oct 26 '06 #4

DataSmash wrote:
Hello,
I need to search and replace 4 words in a text file.
Below is my attempt at it, but this code appends
a copy of the text file within itself 4 times.
Can someone help me out.
Thanks!

# Search & Replace
file = open("text.txt" , "r")
text = file.read()
file.close()

file = open("text.txt" , "w")
file.write(text .replace("Left_ RefAddr", "FromLeft") )
file.write(text .replace("Left_ NonRefAddr", "ToLeft"))
file.write(text .replace("Right _RefAddr", "FromRight" ))
file.write(text .replace("Right _NonRefAddr", "ToRight"))
file.close()
Check out the Pythons standard fileinput module. It also has options
for in-place editing.

(
http://groups.google.com/group/comp....17f004e?hl=en&
)

- Pad.

Oct 27 '06 #5
DataSmash wrote:
Hello,
I need to search and replace 4 words in a text file.
Below is my attempt at it, but this code appends
a copy of the text file within itself 4 times.
Can someone help me out.
Thanks!

# Search & Replace
file = open("text.txt" , "r")
text = file.read()
file.close()

file = open("text.txt" , "w")
file.write(text .replace("Left_ RefAddr", "FromLeft") )
file.write(text .replace("Left_ NonRefAddr", "ToLeft"))
file.write(text .replace("Right _RefAddr", "FromRight" ))
file.write(text .replace("Right _NonRefAddr", "ToRight"))
file.close()

Here's a perfect problem for a stream editor, like
http://cheeseshop.python.org/pypi/SE/2.2%20beta. This is how it works:
>>replacement_d efinitions = '''
Left_RefAddr=Fr omLeft
Left_NonRefAddr =ToLeft
Right_RefAddr=F romRight
Right_NonRefAdd r=ToRight
'''
>>import SE
Replacement s = SE.SE (replacement_de finitions)
Replacement s ('text.txt', 'new_text.txt')
That's all! Or in place:
>>ALLOW_IN_PLAC E = 3
Replacements. set (file_handling_ flag = ALLOW_IN_PLACE)
Replacement s ('text.txt')
This should solve your task.

An SE object takes strings too, which is required for line-by-line
processing and is very useful for development or verification:
>>print Replacements (replacement_de finitions) # Use definitions as
test data

FromLeft=FromLe ft
ToLeft=ToLeft
FromRight=FromR ight
ToRight=ToRight

Checks out. All substitutions are made.
Regards

Frederic
Oct 27 '06 #6
Really appreciate all the all the different answers and learning tips!

Oct 27 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
3307
by: Zenobia | last post by:
Hello I want a search & replace text in source code for several files in several directories. It would seem that both Dreamweaver MX 6 and GoLive 6 offer this feature but not for .aspx file types. Is there a hack that sets the configuration files for one of these programs and fools the program into allowing the global search and replace?
3
3368
by: tchurm | last post by:
Hi Pythonistas, Here's my problem: I'm using a version of MOOX Firefox (http://moox.ws/tech/mozilla/) that's been modified to run completely from a USB Stick. It works fine, except when I install or uninstall an extension, in which case I then have to physically edit the compreg.dat file in my profile directory, replacing all instances of Absolute Path links to relative ones. (And, yes, I have filed a Bugzilla report.) For example,...
1
1971
by: Tomomichi Amano | last post by:
Could some one tell me how I can seach and replace only one word in a textBox (THE FIRST WORD THAT COMES AFTER THE CURSOR). I already know how to replace ALL , but I don't know how to REPLACE one, and how to SEARCH one and select that point. Thank in advance
1
1684
by: Tomomichi Amano | last post by:
Hello. I want to make replace & search functions in my text editor. Thanks to the kind people here at the newsgroup, I was able to make the function. But I was not able to understand how to REPLACE the next word (the nearest word from the cursor; not REPLACE ALL, but replace only one word) and SEARCH the next word. COuld some one help me? Thanks in advance.
3
8263
by: Craig Buchanan | last post by:
Is there a way to combine these two Replace into a single line? Regex.Replace(Subject, "\&", "&amp;") Regex.Replace(Subject, "\'", "&apos;") Perhaps Regex.Replace(Subject, "{\&|\'}", "{&amp;|&apos;}") Thanks, Craig
2
1393
by: Jan | last post by:
Hello! I am looking for a way to do a search&replace in ASCII-Files by a vb.net 2005 programm. Of coarse I can open the files, loop to every line, make a replace, and save the line. But I wonder if there is a better and faster way to do it. To make it clear: The search&replace must be done within a programm not in the Framework or editor.
2
5105
by: Ola K | last post by:
Hi guys, I wrote a script that works *almost* perfectly, and this lack of perfection simply puzzles me. I simply cannot point the whys, so any help on it will be appreciated. I paste it all here, the string at the beginning explains what it does: '''A script for MS Word which does the following: 1) Assigns all Hebrew italic characters "Italic" character style. 2) Assigns all Hebrew bold characters "Bold" character style. 2) Assign all...
16
3044
by: Proaccesspro | last post by:
I'm trying to create a search & replace function in Access. Specifically, I want to search for a specific SSN and replace it, if found. Not sure how to code the "guts" of it. Here is what I have so far: Private Sub CmdUpdateAppeal_Click() SSNreplace = InputBox("Please enter the Member's SSN", "Update a SSN") If SSNreplace = "" Then MsgBox "No Number Entered. Please Try Again", vbCritical, "Update a SSN" End End If
6
2239
by: simon.robin.jackson | last post by:
Ok. I need to develop a macro/vba code to do the following. There are at least 300 corrections and its expected for this to happen a lot more in the future. Therefore id like a nice button that does this all for me. In my head the method should go something like this:
0
9961
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11178
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10777
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10438
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9597
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7148
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5817
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6014
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3251
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.