Hi,
I've encountered a problem iwhile writing a find and replace prg in python.
this is my code:

import re
f = file('testfile')
while True:
	line = f.readline()
	if len(line) == 0:
		break
	print line
	p = re.compile(line)
	m = p.match('METASERV_HOME')
	print m
f.close()

as per the logic :
if my testfile contains METASERV_HOME, then i shld be getting an instance of "matching object"
otherwise , "none"
but instead of the former result, i am getting just none.
i want to know if i have done something wrong in reading a file.
print line....in the prg correctly reads the first line in the textfile.
for testing pupose my textfile has only 2 lines in the file and both of them are METASERV_HOME.

here is the output:

C:\python>python findnreplace.py
METASERV_HOME

None
METASERV_HOME

None

so where wud the problem be.?
kindly help me on this,
Thanks in advance,
Harini

Edit: Added code tags vegaseat

Recommended Answers

All 2 Replies

Hi!

METASERV_HOME is the string you want to find, so you have to re.compile("METASERV_LINE"). Then you ... I'll just show you my snippet :)

import re

p = re.compile("METASERV_HOME")
f = file("d.dat", "r")
for line in f:
    m = p.match(line)
    print m
f.close()

If you just want to know if "ME...." is in your line, then you don't need a regex. You can just write

for line in f:
    if "METASERV_HOME" in line: 
        do_something

If you just want to replace it with something else, it gets even easier:

for line in f:
    line = line.replace("METASERV_HOME", "NEW")
    print line

Hope this helps.

Regards, mawe

I think its new line character at the end of each line which results in mismatch

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.