2

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?

2
  • have you tried regular expressions? Commented Mar 23, 2015 at 13:58
  • 1
    Can you assume that each of the string starts a new line? If so, you could search for "\nx ==" and replace it with "\nx == 5" Commented Mar 23, 2015 at 14:00

4 Answers 4

4

You could use regex here.

with open(file) as f:
    print(re.sub(r'(?m)^x == *$', 'x == 10', f.read()))
Sign up to request clarification or add additional context in comments.

Comments

1

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

0

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

This solution had the same effect of replacing the other line with "xx == ". However, Avinash's solution works fine.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.