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() 6 2665
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
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
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
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.
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
Really appreciate all the all the different answers and learning tips! This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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?
|
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...
|
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
|
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?...
|
by: Craig Buchanan |
last post by:
Is there a way to combine these two Replace into a single line?
Regex.Replace(Subject, "\&", "&")
Regex.Replace(Subject, "\'", "'")
Perhaps Regex.Replace(Subject, "{\&|\'}", "{&|'}")
Thanks,
Craig
| |
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.
|
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...
|
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
...
|
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:
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language...
|
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. ...
| |
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...
|
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...
|
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...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |