473,395 Members | 1,647 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,395 software developers and data experts.

Find and replace in a file with regular expression

Hi everyone,
First I say that I serched and tryed everything but I cannot figure
out how I can do it.
I want to open a a file (not necessary a txt) and find and replace a
string.
I can do it with:

import fileinput, string, sys
fileQuery = "Text.txt"
sourceText = '''SOURCE'''
replaceText = '''REPLACE'''
def replace(fileName, sourceText, replaceText):

file = open(fileName, "r")
text = file.read() #Reads the file and assigns the value to a
variable
file.close() #Closes the file (read session)
file = open(fileName, "w")
file.write(text.replace(sourceText, replaceText))
file.close() #Closes the file (write session)
print "All went well, the modifications are done"

replacemachine(fileQuery, sourceText, replaceText)

Now all went ok but I'm wondering if it's possible to replace text if /
sourceText/ match a regex.
Help me please!
Thx in advance

Jan 30 '07 #1
3 16889
The re module is used for regular expressions. Something like this
should work (untested):

import fileinput, string, sys, re

fileQuery = "Text.txt"
sourceText = '''SOURCE'''
replaceText = '''REPLACE'''

def replace(fileName, sourceText, replaceText):
file = open(fileName, "r")
text = file.read() #Reads the file and assigns the value to a
variable
file.close() #Closes the file (read session)

file = open(fileName, "w")
file.write(re.sub(sourceText, replaceText,text))
file.close() #Closes the file (write session)

print "All went well, the modifications are done"

replacemachine(fileQuery, sourceText, replaceText)

Jan 30 '07 #2
Just in case you didn't think about it there is a plain replace method for strings

How to quick-search this method with 'dir'
>>dir("")
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex',
'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>help("".replace)
Help on built-in function replace:

replace(...)
S.replace (old, new[, maxsplit]) -string

Return a copy of string S with all occurrences of substring
old replaced by new. If the optional argument maxsplit is
given, only the first maxsplit occurrences are replaced.

and now how to apply it:
new_text = open(fileName).read().replace("SOURCE", "REPLACE")

which is the preferred method for a simple task like this.

TOXiC wrote:
Hi everyone,
First I say that I serched and tryed everything but I cannot figure
out how I can do it.
I want to open a a file (not necessary a txt) and find and replace a
string.
I can do it with:

import fileinput, string, sys
fileQuery = "Text.txt"
sourceText = '''SOURCE'''
replaceText = '''REPLACE'''
def replace(fileName, sourceText, replaceText):
Now how to solve it with a simple regular expression:
>>import re
re_replace = re.compile("SOURCE").sub

txt = " SOURCE SOURCE \n SOURCE "

print re_replace("REPLACE", txt)
' REPLACE REPLACE \n REPLACE '
>>new_text = re_replace("REPLACE", open(fileName).read())
A regular expression for this task is kind of overkill. Mastering
regular expression is the efford very worth.

Wolfgang Grafen
Jan 31 '07 #3
TOXiC wrote:
Hi everyone,
First I say that I serched and tryed everything but I cannot figure
out how I can do it.
I want to open a a file (not necessary a txt) and find and replace a
string.
I can do it with:

import fileinput, string, sys
fileQuery = "Text.txt"
sourceText = '''SOURCE'''
replaceText = '''REPLACE'''
def replace(fileName, sourceText, replaceText):

file = open(fileName, "r")
text = file.read() #Reads the file and assigns the value to a
variable
file.close() #Closes the file (read session)
file = open(fileName, "w")
file.write(text.replace(sourceText, replaceText))
file.close() #Closes the file (write session)
print "All went well, the modifications are done"

replacemachine(fileQuery, sourceText, replaceText)

Now all went ok but I'm wondering if it's possible to replace text if /
sourceText/ match a regex.
Help me please!
Thx in advance

Try this:
>>import SE # from http://cheeseshop.python.org/pypi/SE/2.3
>>replacements = 'SOURCE=REPLACE "another source=another replace"
~[0-9]+~=>>int<< ~[0-9]+\\.[0-9]+~=>>float<< ~'
# Define as many replacements as you like. Identify regexes placing
them between '~'
>>Stream_Editor = SE.SE (replacements)
>>Stream_Editor (input_file, output_file)
That's it.
PS 1: Your Stream_Editor accepts strings as well as file names and then
returns a string by default. This is a great help for developing
substitution sets interactively.
>>print Stream_Editor ('''
If it works, this SOURCE should read REPLACE
and another source should become another replace
and this 123456789 should become >>int<<
and this 12345.6789 is a float and so should read >>float<<.''')

If it works, this REPLACE should read REPLACE
and another replace should become another replace
and this >>int<< should become >>int<<
and this >>float<< is a float and so should read >>float<<.

PS 2: It is convenient to keep large and frequently used substitution
sets in text files. The SE constructor accepts a file name instead of
the replacements string:
>>Stream_Edtor = SE.SE ('path/replacement_definitions_file')

Regards

Frederic

Feb 3 '07 #4

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

Similar topics

4
by: higabe | last post by:
Three questions 1) I have a string function that works perfectly but according to W3C.org web site is syntactically flawed because it contains the characters </ in sequence. So how am I...
24
by: Wim Roffal | last post by:
Is there a possibility to do a string replace in javascript without regular experessions. It feels like using a hammer to crash an egg. Wim
1
by: Mark | last post by:
Using the Find and Replace in VS.NET, I'm trying to find methods that are in the form .... Foo** and I want to replace them with: BarFoo** However, put the text above in the Find and...
4
by: JackRazz | last post by:
I'm trying to use Visual Studio's Find/Replace to match VB declarations. This RegEx works fine in Regulator: ...
2
by: JebBushell | last post by:
I see signs that the ASP.NET regular expression validator has a different instruction set that the Find utility in VS 2003. I am trying to use the VS2003 regular expression Find tool to test...
4
by: JackRazz | last post by:
Could someone give me a very simple regular expression for Visual Studio's search/replace using backreferences saving portions of the match as \1 or $1 or whatever. I want to use something I can...
4
by: lucky | last post by:
hi there!! i'm looking for a code snipett wich help me to search some words into a particular string and replace with a perticular word. i got a huge data string in which searching traditional...
8
by: John Pye | last post by:
Hi all I have a file with a bunch of perl regular expressions like so: /(^|)\*(.*?)\*(|$)/$1'''$2'''$3/ # bold /(^|)\_\_(.*?)\_\_(|$)/$1''<b>$2<\/ b>''$3/ # italic bold...
1
by: NvrBst | last post by:
I want to use the .replace() method with the regular expression /^ %VAR % =,($|&)/. The following DOESN'T replace the "^default.aspx=,($|&)" regular expression with "":...
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...
0
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,...
0
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...
0
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,...
0
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...

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.