Tarandeep Kalra
Tarandeep Kalra

Reputation: 377

Python script to replace a string in a particular line

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?

Upvotes: 2

Views: 2822

Answers (4)

user4700203
user4700203

Reputation:

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.

Upvotes: 0

Maxime Chéramy
Maxime Chéramy

Reputation: 18831

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) 

Upvotes: 0

Lie Ryan
Lie Ryan

Reputation: 64837

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.

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

You could use regex here.

with open(file) as f:
    print(re.sub(r'(?m)^x == *$', 'x == 10', f.read()))

Upvotes: 4

Related Questions