Replacing line in a text file

Tim Chase python.list at tim.thechases.com
Fri Sep 22 14:08:50 EDT 2006


> I am trying to read a file
> This file has a line containing string  'disable = yes'
> 
> I want to change this line to 'disable = no'

Sounds like

	sed -i 's/disable *= *yes/disable = no/' file.txt

would do what you want.  It doesn't catch word boundaries, so if 
you have something like "foodisable = yes", it will replace this 
too.  Additionally, it only expects spaces around the equal-sign, 
so if you have tabs, you'd have to modify accordingly.

If it must be done in python,

import re
r = re.compile(r"(\bdisable\s*=\s*)yes\b")
outfile = file('out.txt', 'w')
for line in file('in.txt'):
	outfile.write(r.sub(r'\1no', line))

Add the re.IGNORECASE option if so desired.  This doesn't have 
the cautions listed above for the sed version.  Wreckless code!

> The concern here is that , i plan to take into account the white spaces
> also.

I'm not sure what you intend by this.  Do you want to disregard 
whitespace?  Do you want to keep leading indentation?

The above python should *just* replace "yes" with "no" in the 
above context, not touching space or anything of the like.

-tkc









More information about the Python-list mailing list