I have a file "xyz.txt" and I am writing a python script to replace a string in a particular line. So essentially I have a string which says
x == in one line which I want to replace with x == 10.
In another line I have xx == 5 which I don't want to replace.
When I use the command -
for line in fileinput.input([filename],inplace=True):
line.replace(old string, new string)
where,
old string = "x =="
new string = "x == 5".
This ends up replacing the other line that has xx == 5 that I don't want to modify.
What would be the best way to just modify that one particular line with x ==
rather than modifying all the lines with "x == " string present in them?
-
have you tried regular expressions?birthofearth– birthofearth2015年03月23日 13:58:15 +00:00Commented Mar 23, 2015 at 13:58
-
1Can you assume that each of the string starts a new line? If so, you could search for "\nx ==" and replace it with "\nx == 5"iayork– iayork2015年03月23日 14:00:20 +00:00Commented Mar 23, 2015 at 14:00
4 Answers 4
You could use regex here.
with open(file) as f:
print(re.sub(r'(?m)^x == *$', 'x == 10', f.read()))
Comments
If I answer the title question literally,
blacklist = [... list unwanted line numbers ...]
for lineno, line in enumerate(fileinput.input([filename],inplace=True):
if lineno not in blacklist:
line.replace(old string, new string)
But the other answer suggesting regex is probably what you actually wanted to do.
Comments
The solution proposed by Avinash is probably the best but here's a more easy to understand solution:
for line in fileinput.input([filename],inplace=True):
if line.startswith(old string):
line.replace(old string, new string)
1 Comment
You can do something like this
import re
f = open("C:/Users/Superman/Desktop/krypton.log")
data = f.read()
replaced_line = re.sub(r'\sx ==', ' x==10', data)
print(replaced_line)
using re we can do regular expressions in python. \s will match to the white space therefore xx == 5 will not match. only ' x==' will match.