473,382 Members | 1,362 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

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 2654
In <11**********************@f16g2000cwb.googlegroups .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("Left_RefAddr", "FromLeft")
text = text.replace("Left_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").replace("Left_NonRefAddr",
"ToLeft").replace("Right_RefAddr",
"FromRight").replace("Right_NonRefAddr", "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(target, repl)
dest.write(line)

replacements = [
("Left_RefAddr", "FromLeft"),
("Left_NonRefAddr", "ToLeft"),
("Right_RefAddr", "FromRight"),
("Right_NonRefAddr", "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.txt")

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_definitions = '''
Left_RefAddr=FromLeft
Left_NonRefAddr=ToLeft
Right_RefAddr=FromRight
Right_NonRefAddr=ToRight
'''
>>import SE
Replacements = SE.SE (replacement_definitions)
Replacements ('text.txt', 'new_text.txt')
That's all! Or in place:
>>ALLOW_IN_PLACE = 3
Replacements.set (file_handling_flag = ALLOW_IN_PLACE)
Replacements ('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_definitions) # Use definitions as
test data

FromLeft=FromLeft
ToLeft=ToLeft
FromRight=FromRight
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
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...
3
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...
1
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,...
1
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...
3
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;}")...
2
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...
2
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,...
16
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...
6
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...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.